我是django的新手,我想做“家庭开支”。 我已经做过简单的模型和形式: (来自模特)
#models.py
#these are the type (groceries/clothes/etc. )
class TypWydatku(models.Model):
typ_wydatku = models.CharField(max_length=25)
data_wpisu=models.DateField(auto_now_add=True)
#these are the actual input with dates/prices/etc
class Wpisy(models.Model):
data_zakupu=models.DateField(default=timezone.now())
data_wpisu=models.DateField(auto_now=True)
typ_wydatku=models.ForeignKey(TypWydatku)
kwota=models.FloatField('kwota')
uwagi=models.CharField(max_length=255, blank=True)
但是现在我想添加另一个模型,它将描述与我的汽车相关的费用更具体。所以我添加另一个TypWydatku - Moto id = 3
下一步是创建具有额外字段(里程/油箱)的新车型:
#models.py
(...)
class WpisyMoto(models.Model):
wpis=models.ForeignKey(Wpisy)
przebieg=models.IntegerField()
uwagi=models.CharField(max_length=200)
litry=models.FloatField()
#and more
我有最简单的形式,因为现在可以拥有最严格的形式:
# forms.py
class TypWydatkuForm(ModelForm):
class Meta:
model = TypWydatku
fields = '__all__'
class WpisyForm(ModelForm):
class Meta:
model = Wpisy
fields = '__all__'
class WpisyMotoForm(ModelForm):
class Meta:
model = WpisyMoto
fields = '__all__'
我想在模板中选择字段'wpis',我想只看到'typ_wydatku'= 3。我该怎么办?
答案 0 :(得分:0)
从ModelChoiceField字段的docs(Django将用于表示ForeignKey字段的表单字段类型),可以通过设置表单字段的queryset属性来实现:
class WpisyMotoForm(ModelForm):
class Meta:
model = WpisyMoto
fields = '__all__'
def __init__(self, *args, **kwargs):
super(WpisyMotoForm, self).__init__(*args, **kwargs)
self.fields["wpis"].queryset = Wpisy.objects.filter(typ_wydatku__pk=3)