Saeed Esmaili
Saeed Esmaili

Reputation: 843

Query the items related to current user in template

I have two models in my Django app like the following:

class Movie(models.Model):
    title = models.CharField()
    # some movie-related fields

class Rating(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
    score = models.IntegerField()

So users can rate any movies they want. I have also a templated named index.html and here is how I'm sending the data to this template using the views.py:

def index(request):
    movies_list = Movie.objects.all()
    paginator = Paginator(movies_list, 8)
    page = request.GET.get('page')
    movies = paginator.get_page(page)
    return render(request, 'index.html', {'movies': movies})

The index.html:

{% for movie in movies %}
    {{movie.title}} <br />
    # The rating score that current user has gave to this movie in the iteration
{% endfor %}

I've tried the following, but it displays all scores that all users have given to the movie, not only the current user:

{% for rating in movie.rating_set.all %}
    {{rating.score}}
{% endfor %}

How can I display the score that current user (that is seeing the movie page) has given to the movie in the index.html page?

Upvotes: 1

Views: 62

Answers (1)

Davit Tovmasyan
Davit Tovmasyan

Reputation: 3588

You could solve it with subquery, no need to query from template. Here is how.

from django.db.models import OuterRef, Subquery

def index(request):
    score = Rating.objects.filter(movie=OuterRef('pk'), user=request.user).values('score')
    movies_queryset = Movie.objects.annotate(user_score=Subquery(score[:1]))
    paginator = Paginator(movies_queryset, 8)
    page = request.GET.get('page')
    movies = paginator.get_page(page)
    return render(request, 'index.html', {'movies': movies})

Then just use user_score to access the value.

{% for movie in movies %}
    {{movie.title}} <br />
    {{ movie.user_score }}
{% endfor %}

Upvotes: 1

Related Questions