Alireza Farahani
Alireza Farahani

Reputation: 2539

Derived attribute in Django model

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.

Upvotes: 3

Views: 1211

Answers (1)

Simeon Visser
Simeon Visser

Reputation: 122336

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 }}.

Upvotes: 3

Related Questions