我有像这样的django ForeignKey
class Example(models.Model):
Field = models.CharField("Description", max_length=50)
AnotherField = models.CharField("Extra Info", max_length=50)
def __unicode__(self):
return self.Field
默认情况下,HTML select
将包含Example.Field
字段的值作为描述。我无法改变unicode方法。真正的问题是当我需要另一个值模型时。我需要像这样的东西:
class SecondExapmle(models.Model):
Description = models.CharField("Description", max_length=50)
Foreign = models.ForeignKey(Example)
SecondData = models.ForeignKey(Example, show_value_from_column="AnotherField") # this line
假设SecondExample
有下一条记录:
-----------------------------
| id | field | anotherfield |
-----------------------------
| 1 | Str | Another Str |
| 2 | Str2 | Another2 |
-----------------------------
我需要Form的Foreign选择包含下一个HTML:
<select id="id_foreign">
<option value='1'>Str</option>
<option value='2'>Str2</option>
</select>
Forms AnotherField选择包含下一个HTML:
<select id="id_anotherfield">
<option value='1'>Anotheer Str</option>
<option value='2'>Another2</option>
</select>
答案 0 :(得分:0)
documentation for forms.ModelChoiceField
- 用于表单上的ForeignKey的字段 - 显示了此处的确切操作。您需要对表单字段进行子类化并定义label_from_instance
方法。
答案 1 :(得分:0)
使用verbose_name=''
:
models.ForeignKey(Example, verbose_name='Example')