3

I have these two models:

class Product(models.Model):

    category = models.ForeignKey('Category')

    name = models.CharField(max_length=60, verbose_name=u'نام کالا')
    price = models.PositiveIntegerField(verbose_name=u'قیمت')
    image = models.ImageField(upload_to='products_images', verbose_name=u'عکس')
    #score ???

    def get_score(self):
        pass


class Review(models.Model):

    product = models.ForeignKey('Product')

    rating = models.PositiveSmallIntegerField(max_length=1, verbose_name=u'امتیاز')

How can I have a derived attribute for Product called score, so when I call product.score it calls the get_score function and returns the average score calculated from Review model?
For example if a product has two reviews with scores 4 and 2, I want to product.score returns 3.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
Alireza Farahani
  • 2,238
  • 3
  • 30
  • 54

1 Answers1

2

If you name your method score you could use a property:

@property
def score(self):
    pass

and this means product.score will return the result of that method. However this all takes place outside of Django's ORM so it wouldn't be recognized as a field on your model. Nonetheless it works in your Python code and in your templates you could use {{ product.score }}.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180