Yian
Yian

Reputation: 199

Display values from foreign key in Django Admin

I am trying to show values from a foreign key in my model value (in admin).

I am using "except" tho I am I should use explicit. How do I use this? And how to I get the below working correctly? It just shows (none) but there is a value there.

Thanks

Admin.py

----------------------
    def price(self, obj):
        try:
            price = Price.objects.filter(variation=Variation.objects.filter(product=obj)[0])
        except:
            price = 'None'
        return format_html('<center><b>"{0}"</b></center>', price.price)

Models.py

--------

class Product(models.Model):
    name = models.CharField ("Name", max_length=130)
    link = models.URLField("Link", max_length=740)

class Variation(models.Model):
    product = models.ForeignKey(Product, blank=False, null=False)
    variation = models.CharField (max_length=80, blank=True, null=True)
    def __str__(self):
        return self.variation

class Price(models.Model):
    price = models.DecimalField("Price", decimal_places=2, max_digits=10)
    variation = models.ForeignKey(Variation, blank=False, null=False)
    updated = models.DateTimeField(auto_now=True)
    def __int__(self):
        return self.price

Upvotes: 0

Views: 928

Answers (1)

Tomasz Jakub Rup
Tomasz Jakub Rup

Reputation: 10680

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)

Upvotes: 1

Related Questions