Django, how to get attribute of forignkey related object

Viewed 499

I have below models,

class Model_1(models.Model)
     price = models.IntergerField()

class Model_2(models.Model)
    product=models.ForeignKey(Model_1)
    quantity = models.IntergerField()
   
    @property
    def totalprice(self):
        return self.quantity * self.product__price

arr = [obj1,obj2,obj3] # objects of Model_2

I am getting error that arr objects has no attribute 'product__price'

1 Answers

You access the attributes of the related product:

class Model_2(models.Model)
    product = models.ForeignKey(Model_1)
    quantity = models.IntergerField()
   
    @property
    def totalprice(self):
        return self.quantity * self.product.price

A ForeignKey lazily loads the related object, so if you fetch self.product, it will make a query, and load the related Model_1 object in memory, you can then access the attributes of that object.

Related