如何在 Django Admin 中更改 ForeignKey 显示文本? [英] How to change ForeignKey display text in the Django Admin?
问题描述
如何在选择 ForeignKey
字段时更改 <select>
字段中的显示文本?
How can I change the display text in a <select>
field while selecting a field which is a ForeignKey
?
我不仅需要显示 ForeignKey
的名称,还需要显示其父项的名称.
I need to display not only the name of ForeignKey
, but also the name of it's parent.
推荐答案
如果你希望它只在 admin 中生效,而不是全局生效,那么你可以创建一个自定义的 ModelChoiceField
子类,使用它在自定义 ModelForm
中,然后设置相关的管理类以使用您的自定义表单.使用一个示例,该示例具有 @Enrique 使用的 Person
模型的 ForeignKey:
If you want it to take effect only in admin, and not globally, then you could create a custom ModelChoiceField
subclass, use that in a custom ModelForm
and then set the relevant admin class to use your customized form.
Using an example which has a ForeignKey to the Person
model used by @Enrique:
class Invoice(models.Model):
person = models.ForeignKey(Person)
....
class InvoiceAdmin(admin.ModelAdmin):
form = MyInvoiceAdminForm
class MyInvoiceAdminForm(forms.ModelForm):
person = CustomModelChoiceField(queryset=Person.objects.all())
class Meta:
model = Invoice
class CustomModelChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return "%s %s" % (obj.first_name, obj.last_name)
这篇关于如何在 Django Admin 中更改 ForeignKey 显示文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!