查询模板中与当前用户相关的项目

时间:2019-01-02 12:46:00

标签: python django

我的Django应用中有两个模型,如下所示:

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()

因此用户可以为他们想要的任何电影评分。 我还有一个名为index.html的模板,这是使用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})

index.html

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

我尝试了以下操作,但它显示了所有用户给电影提供的所有乐谱,而不仅仅是当前用户:

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

如何在index.html页面上显示当前用户(正在查看电影页面)对电影的得分?

1 个答案:

答案 0 :(得分:1)

您可以使用子查询来解决它,而无需从模板中查询。这就是方法。

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})

然后仅使用user_score访问该值。

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