Query to fetch highest rated movie with mimimum 5 people rated

强颜欢笑 提交于 2020-01-16 08:35:50

问题


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 ForeignKeys 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 Movies 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:

  1. Count(Rate for the exact Movie) > minimum threshold(e.g. 5)
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!