【问题标题】:Check if element is in a model - Django templates检查元素是否在模型中 - Django 模板
【发布时间】:2021-02-26 10:57:00
【问题描述】:

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

我正在为模板尝试这个: 如果用户喜欢这篇文章。那个帖子显示的是一颗充满的心,否则它只显示一个心脏轮廓

{% 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,即使用户实际上喜欢该帖子。

这是模型:

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

我正在通过渲染传递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}})中打印它,则会出现查询集,因此上下文可以正常传递。 我不知道为什么条件不检查数据库中元素的存在

【问题讨论】:

  • likelist 是一组Likelist 对象,postPost 对象,所以Post 对象永远不能在likelist 中。

标签: python html django templates model


【解决方案1】:

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(
        likes=OuteRef('pk'), user=user_id
    ))
).order_by('-timestamp')

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

然后在模板中检查:

{% for post in posts %}
   {% if post.is_liked %}
      …
   {% else %}
      …
   {% endif %} 
{% endfor %}

注意:通常 Django 模型被赋予一个单数名称,所以Post而不是Posts

【讨论】:

    猜你喜欢
    • 2011-09-07
    • 2019-09-01
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    相关资源
    最近更新 更多