如何更改Django models.ForeignKey的默认描述

时间:2014-08-14 17:29:40

标签: python django django-models django-forms

我有像这样的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>

2 个答案:

答案 0 :(得分:0)

documentation for forms.ModelChoiceField - 用于表单上的ForeignKey的字段 - 显示了此处的确切操作。您需要对表单字段进行子类化并定义label_from_instance方法。

答案 1 :(得分:0)

使用verbose_name=''

models.ForeignKey(Example, verbose_name='Example')