问题
I want to fetch name of movie with maximum rated movie with minimum 5 people rated in django. My code :
model.py
class Movie(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=100)
vote_count = models.IntegerField()
class Watchlist(models.Model):
userid = models.IntegerField()
movie_id = models.ForeignKey(Movie, on_delete=models.CASCADE)
rating = models.IntegerField()
what will be query to get movie with highest rating with minimum 5 people ?
回答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
class Movie(models.Model):
title = models.CharField(max_length=100)
class Rating(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.
回答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
来源:https://stackoverflow.com/questions/59728819/query-to-fetch-highest-rated-movie-with-mimimum-5-people-rated