我有一个模型,其中一个字段引用另一个模型中的外键:
class DummyModel(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=150)
image_type = models.ForeignKey(ImageTypeModel) # Foreign key
class Meta:
db_table = "dummy"
父模型也很简单:
class ImageTypeModel(models.Model):
name = models.CharField(max_length=100)
dims = models.IntegerField()
class Meta:
db_table = "imagetypes"
现在,我尝试在表单中呈现记录,为此我正在使用django-crispy-forms
。所以,我有:
class DummyForm(ModelForm):
class Meta:
model = DummyModel
fields = ['name', 'description', 'image_type']
def __init__(self, *args, **kwargs):
super(DummyForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-sm-2'
self.helper.field_class = 'col-sm-10'
#self.helper.form_tag = False
self.helper.layout = Layout(
Field('name'),
Field('description'),
Field('image_type'))
image_type
字段呈现为完美的下拉列表,但不是图像类型的名称,条目都标记为ImageTypeModel
。是否有一种机制,以便我可以显示来自ImageTypeModel
记录的相应名称,但是当保存表单时,它会保存主键而不是名称。
答案 0 :(得分:3)
您应该在模型中实现__unicode__
(python 2)或__str__
(python 3)方法。
像这样:
class ImageTypeModel(models.Model):
name = models.CharField(max_length=100)
dims = models.IntegerField()
class Meta:
db_table = "imagetypes"
# For Python 2
def __unicode__(self):
return self.name
# For Python 3
def __str__(self):
return self.name