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


Let’s try to simplify your code.


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:

    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