【发布时间】:2017-07-02 07:19:57
【问题描述】:
我有一个 ModelForm,我可以在其中显示作为下拉列表 ({{ form.auto_part }}) 或 value 的外键字段或作为数字 ({{ form.auto_part.value }}) 的外键字段的 ID .但我想显示外键字段的__str__ 值。我该怎么做?
forms.py
class AddCostPriceForm(forms.ModelForm):
class Meta:
model = Product
fields = ['auto_part', 'cost_price']
models.py
class Product(Timestamped):
product_list = models.ForeignKey(List)
auto_part = models.ForeignKey(AutoPart)
quantity = models.SmallIntegerField()
unit = models.CharField(max_length=20, default='pcs')
cost_price = models.IntegerField(blank=True, null=True)
class AutoPart(Timestamped):
brand = models.ForeignKey(Brand)
auto_type = models.ForeignKey(AutoType)
part_no = models.CharField(max_length=50)
description = models.CharField(max_length=255)
def __str__(self):
return "{brand} {auto_type} - {part_no}".format(brand=self.brand, auto_type=self.auto_type, part_no=self.part_no)
【问题讨论】:
标签: python django forms templates