In Django debug toolbar points to the following lines:
1)
/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 }}
main/models.py 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']
else:
return 0
users/models.py
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):
UserGameRating.objects.update_or_create(
game=game,
profile=self,
defaults={'rating': rating}
)
game.average_rating = game.usergamerating_set.aggregate(Avg('rating'))['rating__avg']
game.save()
views.py
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