0

I have been trying to find the avg for rating a get queryset.

This is my models.py

class Movie(models.Model):
    title = models.CharField(max_length=240)
    release = models.DateField(blank=True)
    review = models.TextField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    poster = models.FileField(null=True, blank=True)
    poster_wide = models.FileField(null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)


    def comment_count(self):
       return self.comment_set.count()

    def rating_avg(self):
       rate = self.rating.aggregate(Avg('rating'))
       return rate['rating__avg']

class Rating(models.Model):
    movie = models.ForeignKey(Movie,on_delete=models.CASCADE,related_name='rating')
    rating = models.IntegerField(choices=rating_choices, default=5)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)

Code in views.py

def home(request):
    top_movies = Movie.objects.annotate(avg = Avg('rating')).order_by('avg')[:5]
    context = {
              'top_movies': top_movies,
         }
    return render(request, 'home.html', context)

I need to find the top 5 rated movies from this given models. But don't know how to group query can find average. The above query does not provide the correct answer. Any links to other answers or documentation that I can refer?

Gokul
  • 68
  • 1
  • 10

2 Answers2

2

Tried almost everything, Finally found one. This gives the required queryset with movieobjects

top_movies = Movie.objects.annotate(avg=Avg("rating__rating")).order_by('-avg')[:5]
Gokul
  • 68
  • 1
  • 10
0

Completely and totally spitballing here, as I can't really test this on my end, but maybe you can reach the Movie through the Rating, since it is the model that contains the ForeignKey to the other.

Rating.objects.values('movie').annotate(avg=Avg('rating')).order_by('avg')

or

Rating.objects.annotate(avg=Avg('rating'), 
                        movie=Rating.objects.values('movie')).order_by('avg')
cyniikal
  • 134
  • 1
  • 6
  • The first one returns a list not a *queryset*, which i need and second one gives a *AttributeError: 'Query' object has no attribute 'output_field'* – Gokul Aug 14 '18 at 04:53