我无法获得“ list_display”来显示相关表中的字段。
models.py
class product(models.Model):
product_id = models.AutoField(primary_key=True)
EAN = models.CharField(unique=True, editable=False, max_length=13)
Product_name = models.CharField(max_length=50)
class price(models.Model):
price_id = models.AutoField(primary_key=True)
EAN = models.ForeignKey(product, to_field="EAN", on_delete=models.CASCADE)
Vendor = models.ForeignKey(vendor, to_field="Vendor_name", on_delete=models.CASCADE)
Qty = models.CharField(max_length=15)
Price = models.DecimalField(max_digits=8, decimal_places=2, null=True)
panels = [
FieldPanel('EAN'),
FieldPanel('Vendor'),
FieldPanel('Qty'),
FieldPanel('Price'),
]
hooks.py
class price_admin(ModelAdmin):
model = pricelist
menu_label = 'price'
menu_icon = 'pilcrow'
menu_order = 300
add_to_settings_menu = False
exclude_from_explorer = False
list_display = ('EAN_id', 'Vendor_id', 'Price') # <-Here I have a problem
list_filter = ('Vendor_id__Name',)
search_fields = ('Vendor_id__Name', 'EAN_id__EAN')
我可以让“ Vendor_id__Name” 在“ list_filter” 和“ search_fields” 中工作,但是当我将 >“ Vendor_id__Name” 到 list_display ,出现此错误:
AttributeError: Unable to lookup 'EAN_id__Product_name' on price or price_admin
那么,从相关表显示字段(在我的情况下为Vendor_id__Name)的正确方法是什么? 任何帮助将不胜感激!
答案 0 :(得分:1)
正如Ivan Starostin注意到的那样,您在相关的字段名称中有错字。您可以使用的其他选项-方法字段或基本上-list display可以接受的可调用对象:
class price_admin(ModelAdmin):
...
list_display = ('vendor_name', # other fields)
def vendor_name(self, obj):
return obj.EAN.Product_name
vendor_name.short_description = 'Vendor name'