Reputation: 9
I have 2 models
class Movie(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=100)
vote_count = models.IntegerField()
def __str__(self):
return self.title
class Watchlist(models.Model):
userid = models.IntegerField()
movie_id = models.ForeignKey(Movie, on_delete=models.CASCADE)
rating = models.IntegerField()
def __int__(self):
return self.userid
what will be query to fetch highest watched movie
Upvotes: 0
Views: 65
Reputation: 5669
from django.db.models import Count
# the most watched Movie instance
the_most_watched_movie = Movie.objects.annotate(count=Count('watchlist')).order_by('-count').first()
Also it could be done via Watchlist
if you would need it for some reason
watchlist = Watchlist.objects.annotate(count=Count('userid')).values('movie_id', 'count').order_by('-count').first()
movie_id = watchlist['movie_id'] # the most watched movie id
# the most watched Movie instance
the_most_watched_movie = Movie.objects.get(id=movie_id)
Upvotes: 1