简体   繁体   中英

Generate average for ratings in Django models and return with other model

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?

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'))
)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM