Reputation: 5664
I'm working on a project using Python(3.7) and Django(2.1) in which I'm trying to implement a rating system.
Note: I have searched a lot and taken a look at various related questions but couldn't find any solution to my specific problem, so don't mark this as duplicated, please!
I have two models as:
From models.py
:
class Gig(models.Model):
CATEGORY_CHOICES = (
('GD', 'Graphic & Design'),
('DM', 'Digital Marketing'),
('WT', 'Writing & Translation'),
('VA', 'Video & Animation'),
('MA', 'Music & Audio'),
('PT', 'Programming & Tech'),
('FL', 'Fun & Lifestyle'),
)
title = models.CharField(max_length=500)
category = models.CharField(max_length=255, choices=CATEGORY_CHOICES)
description = models.CharField(max_length=1000)
price = models.IntegerField(blank=False)
photo = models.FileField(upload_to='gigs')
status = models.BooleanField(default=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
created_at = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
class GigReview(models.Model):
RATING_RANGE = (
('1', '1'),
('2', '2'),
('3', '3'),
('4', '4'),
('5', '5')
)
user = models.ForeignKey(User, on_delete=models.CASCADE)
gig = models.ForeignKey(Gig, on_delete=models.CASCADE, related_name='rates')
order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True)
rating = models.IntegerField(choices=RATING_RANGE,)
content = models.CharField(max_length=500)
def __str__(self):
return self.content
From views.py
:
def home(request):
gigs = Gig.objects.filter(status=True)
return render(request, 'home.html', {'gigs': gigs})
So, every Gig
has many reviews and I want to return the average
rating for each gig to the template, how Can I achieve that?
Upvotes: 0
Views: 1666
Reputation: 3611
If you want to be able to access the average review value on model level, you could add a property field that aggregates the average value through related models in the Gig
-model:
class Gig(models.Model):
...
@property
def average_rating(self):
return self.rates.all().aggregate(Avg('rating')).get('rating__avg', 0.00)
# Change 0.00 to whatever default value you want when there
# are no reviews.
And in the template access the value with average_rating
.
Upvotes: 3
Reputation: 5740
A simple annotation should get it done in one query (rather than one per Gig
when using a property):
from django.db.models import Avg
gigs = (Gig.objects
.filter(status=True)
.annotate(avg_review=Avg('rates__rating'))
)
Upvotes: 2