如何在Django Admin中更改ForeignKey显示文本? [英] How to change ForeignKey display text in the Django Admin?
问题描述
如何在< select>中更改显示文本字段,同时选择一个 ForeignKey
?
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.
推荐答案
如果您希望它仅在管理员,而不是全局管理员,则可以创建一个自定义 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屋!