检查元素是否在模型中 - Django 模板

Check if element is in a model - Django templates

我正在尝试制作一个赞按钮。一切正常,除了我无法检查(在模板内)用户是否已经喜欢某些东西。换句话说,我无法检查数据库中的现有行。

我正在为模板尝试这个: 如果用户喜欢post。那post显示的是填充的心形,否则只显示心形轮廓

{% for post in posts %}
   {% if post in likelist %}
      <i class="fa fa-heart like" data-id="{{ post.id }}" id="like-{{ post.id }}" style="color:red;"></i>
   {% else %}
      <i class="fa fa-heart-o like" data-id="{{ post.id }}" id="like-{{ post.id }}" style="color:red;"> 
   </i>
   {% endif %} 
{% endfor %}

但是 if 语句总是给出 False,即使用户实际上喜欢 post。

这是模型:

class Likelist(models.Model):
    user = models.ForeignKey('User', on_delete=models.CASCADE, related_name='liker')
    likes = models.ForeignKey('Posts', on_delete=models.CASCADE, related_name='likes')

    def __str__(self):
        return f"{self.user} likes {self.likes}"

我正在通过 render

传递 views.py 中的上下文
return render(request, "network/profile.html", {
      #[...]some other contexts
      "posts": Posts.objects.filter(user=user_id).order_by('-timestamp'), 
      "likelist": Likelist.objects.filter(user=request.user),
    })

如果我尝试在 HTML 标签({{likelist}} 或 {{posts}} 中打印它,则会出现查询集,因此上下文正常传递。 我不知道为什么条件不检查数据库中元素的存在

likelistLikelist对象的集合,postPost对象,所以一个Post 对象永远不能在 likelist.

但即使是这样,检查成员身份也不是一个好主意,因为它会对每个 Post 对象进行额外的查询。您可以注释 Posts 并检查它们是否喜欢 Exists subquery [Django-doc]:

from django.db.models import Exists, OuterRef

posts = Posts.objects.filter(
    user=user_id
).annotate(
    is_liked=Exists(Likedlist.objects.filter(
        <b>likes=OuteRef('pk'), user=user_id</b>
    ))
).order_by('-timestamp')

return render(request, 'network/profile.html', {
    'posts': posts,
})

然后在模板中,您检查:

{% for post in posts %}
   {% if <b>post.is_liked</b> %}
      …
   {% else %}
      …
   {% endif %} 
{% endfor %}

Note: normally a Django model is given a singular name, so Post instead of Posts.