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.
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 }}.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With