Django管理员 - 更改ForeignKey显示文本 [英] Django admin - change ForeignKey display text

查看:349
本文介绍了Django管理员 - 更改ForeignKey显示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在选择一个作为ForeignKey的字段时更改选择中的显示文本?
我不仅需要显示FK的名称,还要显示它的父名称。



任何人都可以给出一个线索?

$ b $那么如果你想让它只在管理员而不是全局地生效,那么你可以创建一个自定义的 ModelChoiceField 子类,在自定义的 ModelForm 中使用它,然后设置相关的管理类以使用您的自定义表单。
以@Enrique使用的 Person 模型的FK为例:

 类发票(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 =发票

class CustomModelChoiceField(forms.ModelChoiceField):
def label_from_instance(self,obj):
返回%s%s% obj.first_name,obj.last_name)


How can I change the display text in select while selecting a field which is as ForeignKey? I need to display not only the name of FK, but also name of it's parent.

Anybody can give a clue?

解决方案

Well 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. Taking an example which has FK 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管理员 - 更改ForeignKey显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆