2 选项。
选项1:
创建一个新的field
,复制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。
更改. _ _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