判断对象是否在一组模型外键中?

时间:2014-09-19 17:03:58

标签: django django-models django-templates

这是我的models.py:

class Blog(models.Model):
    user = models.ForeignKey(User)
    actualBlog = models.CharField(max_length=200)

class BlogComments(models.Model):
    user = models.ForeignKey(User)
    blog = models.ForeignKey(Blog)
    actualBlog = models.CharField(max_length=200)

我将所有现有博客的列表传递给了我的模板。在我的模板中,我想查看request.user是否在博客评论的用户列表中。像这样:

{% for blog in allExistingBlogs %}
    {% if request.user in blog.blogcomments_set.all %}
        <p>you have already commented on this blog</p>
    {% else %}
        <p>you have not commented on this blog yet</p>
    {% endif %}
{% endfor %}

但这不起作用。我也试过

    {% if request.user in blog.blogcomments_set.all.user %}

但这也不起作用。关于如何让它发挥作用的任何想法?

2 个答案:

答案 0 :(得分:2)

在将视频发送到模板之前,先装饰视图中的对象:

def show_blogs(request):
    all_blogs = Blog.objects.all()
    blogs = []
    for blog in all_blogs:
       blogs.append((blog, blog.blogcomments_set.all(),
                           blog.blogcomments_set.filter(user=request.user).count()))
    return render(request, 'blogs.html', {'blogs': blogs})

现在,在您的模板中:

{% for blog, comments, commented in blogs %}
   {{ blog }} - {{ comments.count }}
   {% if commented %}
       You have already commented!
   {% else %}
       Would you like to comment?
   {% endif %}
{% endfor %}

答案 1 :(得分:1)

您可以在Blog中使用模型方法:

def _get_commenters(self):
    commenters = self.blogcomments_set.values_list(user, flat=True)
    return commenters
commenters = property(_get_commenters)

然后你只需在模板中使用它:

{% if request.user in blog.commenters %}