如何让 Django Admin 呈现外键值而不是 Object 对象
How to have Django Admin render foreign key value instead of Object object
在查看 Django 1.8 中的管理页面时,我对如何正确引用外键值有点不知所措。
我得到了什么:
请注意,外键在左列中正确显示,但在右列中不正确(用于验证),当您单击其中一条记录时也不会显示,这是我要求它显示的位置。
我想要什么:
我希望第二张图片显示 4147128
而不是 WorldEaseConsignee object
。
代码
admin.py
from django.contrib import admin
from .models import WorldEaseConsignee, WorldEaseInvoice
class WorldEaseConsigneeAdmin(admin.ModelAdmin):
list_display = (
'order_number',
)
class WorldEaseInvoiceAdmin(admin.ModelAdmin):
@staticmethod
def get_order_number(obj):
return obj.order_number.order_number
list_display = (
'get_order_number', 'order_number_id'
)
search_fields = [
'order_number__order_number',
]
admin.site.register(WorldEaseConsignee, WorldEaseConsigneeAdmin)
admin.site.register(WorldEaseInvoice, WorldEaseInvoiceAdmin)
models.py 子集
class WorldEaseInvoice(models.Model):
class Meta:
verbose_name = 'WorldEase Invoice List'
verbose_name_plural = 'WorldEase Invoice List'
unique_together = ('order_line', 'order_number')
order_number = models.ForeignKey(
WorldEaseConsignee,
to_field='order_number',
)
def __unicode__(self):
return self.name
class WorldEaseConsignee(models.Model):
class Meta:
verbose_name = 'WorldEase Consignee List'
verbose_name_plural = 'WorldEase Consignee List'
order_number = models.IntegerField(
null=False,
blank=False,
default=0,
unique=True,
)
def __unicode__(self):
return self.order_number # I've also tried self.name
由于您使用的是 Python 3,因此您应该定义 __str__
方法而不是 __unicode__
。
在查看 Django 1.8 中的管理页面时,我对如何正确引用外键值有点不知所措。
我得到了什么:
我想要什么:
我希望第二张图片显示 4147128
而不是 WorldEaseConsignee object
。
代码
admin.py
from django.contrib import admin
from .models import WorldEaseConsignee, WorldEaseInvoice
class WorldEaseConsigneeAdmin(admin.ModelAdmin):
list_display = (
'order_number',
)
class WorldEaseInvoiceAdmin(admin.ModelAdmin):
@staticmethod
def get_order_number(obj):
return obj.order_number.order_number
list_display = (
'get_order_number', 'order_number_id'
)
search_fields = [
'order_number__order_number',
]
admin.site.register(WorldEaseConsignee, WorldEaseConsigneeAdmin)
admin.site.register(WorldEaseInvoice, WorldEaseInvoiceAdmin)
models.py 子集
class WorldEaseInvoice(models.Model):
class Meta:
verbose_name = 'WorldEase Invoice List'
verbose_name_plural = 'WorldEase Invoice List'
unique_together = ('order_line', 'order_number')
order_number = models.ForeignKey(
WorldEaseConsignee,
to_field='order_number',
)
def __unicode__(self):
return self.name
class WorldEaseConsignee(models.Model):
class Meta:
verbose_name = 'WorldEase Consignee List'
verbose_name_plural = 'WorldEase Consignee List'
order_number = models.IntegerField(
null=False,
blank=False,
default=0,
unique=True,
)
def __unicode__(self):
return self.order_number # I've also tried self.name
由于您使用的是 Python 3,因此您应该定义 __str__
方法而不是 __unicode__
。