在查看Django 1.8中的Admin页面时,我对如何正确引用外键值感到有些失落。
我得到了什么:
请注意,外键在左列中正确显示,但在右侧不显示(用于验证),也不会在您单击其中一个记录时显示,这是我要求它显示的位置。
我想要什么:
我希望第二张图片显示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 subset
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
答案 0 :(得分:2)
由于您使用的是Python 3,因此您应该定义__str__
个方法,而不是__unicode__
。