I can't get rid of 6 similar and 6 duplicates(SQL queries)

In Django debug toolbar points to the following lines:
/PycharmProjects/games/main/views.py in get_context_data(74)
context[‘average_rating’] = self.object.get_average_rating()

/PycharmProjects/games/main/models.py in get_average_rating(58)
if ratings.count() > 0:

PycharmProjects/games/main/models.py in get_average_rating(59)
return ratings.aggregate(avg_rating=Avg(‘rating’))[‘avg_rating’]

if ratings.count() > 0:

{% if game.get_average_rating %}

Average rating: {{ game.get_average_rating|floatformat:1 }}

   def get_average_rating(self):
        Average game rating.
        ratings = self.usergamerating_set.all().select_related('rating')
        if ratings.count() > 0:
            return ratings.aggregate(avg_rating=Avg('rating'))['avg_rating']
            return 0


    def get_rating_for_game(self, game):
        rating, created = UserGameRating.objects.get_or_create(game=game, profile=self)
        return rating.rating if rating else None

    def rate_game(self, game, rating):
            defaults={'rating': rating}

        game.average_rating = game.usergamerating_set.aggregate(Avg('rating'))['rating__avg']


    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        comments = Comment.objects.filter(game=self.object).select_related('author', 'game')
        for comment in comments:
            comment.str_value = comment.text
        context['comments'] = comments
        context['game'] = self.object
        context['average_rating'] = self.object.get_average_rating()
        context['form'] = CommentForm
        return context

Hello there, you mentioned that you ran into 6 similar and duplicate SQL queries without actually providing the duplicated SQL which makes very hard for anyone to help you.

From what I can decipher from your request (please take a minute to format the traceback as well when posting them) I would provide two recommendations

  1. In your template use average_rating instead of game.average_rating. You already inject it in the context data so there is not point in recomputing two other times in your template.
  2. There is no reason to materialize the count() query in your get_average_rating method as aggregate functions are able to deal with empty sets. Simply do
def get_average_rating(self):
    return self.usergamerating_set.aggregate(
        avg_rating=Avg('rating', default=0)

Thanks, it really worked. About “without actually providing the duplicated SQL” I should have taken screenshots from the Debug toolbar?

Providing the exact SQL as text (copy paste in code blocks) would be preferable over screenshots.