2 个选项。
选项1:
创建一个新的field
, copy forms.ModelChoiceField
并覆盖label_from_instance
.
# From the source
class PageModelChoiceField(forms.ModelChoiceField():
def label_from_instance(self, obj):
"""
This method is used to convert objects into strings; it's used to
generate the labels for the choices presented by this object. Subclasses
can override this method to customize the display of the choices.
"""
# Then return what you'd like to display
return "Page{0} - Test{1}".format(obj.pk, obj.test.pk)
这只会更改该特定下拉字段的文本。当您访问Test
列表中每个项目的对象,您可能需要确保queryset
你传递到PageModelChoiceField
has select_related('test')
,否则它将对列表中的每个项目进行数据库命中。
我还没有测试过这个确切的代码,但逻辑是存在的。稍后我可以尝试一下
class QuestionForm(forms.ModelForm):
page = PageModelChoiceField(
queryset=Page.objects.select_related('test').all()
)
class Meta:
model = Page
class QuestionAdmin(ModelAdmin):
class Meta:
model = Question
form = QuestionForm
选项B。
改变unicode() 代表Page
.
class Page(models.Model):
test = models.ForeignKey(Test)
def __unicode__(self):
return "Page{0} - Test{1}".format(obj.pk, obj.test.pk)
这将改变如何Page
s 显示在打印页面对象的任何地方,print(page_object)
, {{ page_object }}
.
我个人更喜欢选项1