[Fixed]-Display values from foreign key in Django Admin

1đź‘Ť

âś…

Let’s try to simplify your code.

Instead:

price = Price.objects.filter(variation=Variation.objects.filter(product=obj)[0])

You can write:

price = Price.objects.filter(variation__product=obj)

Filter return QuerySet, but You want to have one price:

price = Price.objects.filter(variation__product=obj)[0]

When no price found, You want to write None, else price.price:

try:
    price = Price.objects.filter(variation__product=obj)[0].price
except Price.DoesNotExist:
    price = 'None'
return format_html('<center><b>"{0}"</b></center>', price)

And finally “explicit” version:

prices = Price.objects.filter(variation__product=obj)
price = prices[0].price if prices.exists() else 'None'
return format_html('<center><b>"{0}"</b></center>', price)

Leave a comment