SilentDev
SilentDev

Reputation: 22747

determine if object is in a set of a models foreign key?

This is my 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)

I passed a list of all the existing blogs to my template. In my template, I want to see if request.user is in the list of users who have commented on the blog. Something like this:

{% 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 %}

but that doesn't work. I also tried

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

but that doesn't work either. Any idea on how to get it to work?

Upvotes: 0

Views: 80

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174614

Decorate the object in your view, before you send it to your template:

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

Now, in your template:

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

Upvotes: 2

Paulo Almeida
Paulo Almeida

Reputation: 8061

You can use a model method in Blog:

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

Then you just use that in the template:

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

Upvotes: 1

Related Questions