【发布时间】:2018-02-22 04:36:38
【问题描述】:
我有以下模型,其中包含 m2m 字段,登录的用户可以对出版物表现出兴趣:
models.py
from django.db import models
class Publication:
title = models.CharField(max_lenth=512)
users_interested = models.ManyToManyField(User)
views.py
from django.shortcuts import render
from django.views import View
from .models import Publication
class listPublicationView(View):
def get(self, request, *args, **kwargs):
publications = Publication.objects.all()
return render(request, "base.html", {'publications': publications})
现在,当登录用户已经对出版物感兴趣时,我尝试在模板中生成“我已经感兴趣”:
base.html
{% for publication in publications %}
{{publication.title}}
{% if currently logged in User is interested in publication (check users_interested) %}
i am already interested
{% endif %}
{% endfor %}
我在想这样的事情:
{% if user.id in publication.users_interested__id %}
【问题讨论】:
-
您必须在视图中加载您想要的信息。该模板不是用来生成任何东西的(除了 html、ofc)。在您的情况下,可能是某种形式的
prefetch_related()或annotate()。