Query To Fetch Highest Rated Movie With Mimimum 5 People Rated
Solution 1:
I propose that you make some changes to your model. Normally ForeignKey
s do not end with an id
suffix, since Django will add a "twin field" with an _id
suffix that stores the value of the target field. Furthermore you probably better make a ForeignKey
to the user model. If you do not specify a primary key yourself, Django will automatically add an field named id
that is an AutoField
, hendce there is no need to add that manually. Finally you do not need to store the vote_count
in a field of the Movie
, you can retrieve that by counting the number of related Rating
objects:
from django.conf import settings
classMovie(models.Model):
title = models.CharField(max_length=100)
classRating(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete.models.CASCADE)
movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
rating = models.IntegerField()
Then we can retrieve the highest rated movie with:
from django.db.models import Avg, Count
higest_rated = Movie.objects.annotate(
rating=Avg('rating__rating'),
votes=Count('rating')
).filter(votes__gte=5).order_by('-rating').first()
Here the votes__gte=5
will filter such that it will only obtain Movie
s with five or more votes, and we order by rating
in descending order.
Solution 2:
I'd modify the model, moving out Rating entity related fields from Watchlist and Movie.
Add the "Rate" class, and then filter by two conditions:
- Count(Rate for the exact Movie) > minimum threshold(e.g. 5)
- AVG(rating score for the exact Movie) > minimum threshold(e.g. 5) or, if you need top-rated movies, use Order by as it described in that answer
In your case, you could use Count and Average with Watchlist.Rating field
Post a Comment for "Query To Fetch Highest Rated Movie With Mimimum 5 People Rated"