Taziamoma Abraham
Taziamoma Abraham

Reputation: 67

Queryset filter by variable that's in another queryset

I am trying to filter a queryset by a variable in another queryset that hasn't been set yet. I know it sounds confusing so let me show you.

Views.py

def ViewThreadView(request, thread):
    posts = Post.objects.filter(post_thread=thread)
    thread = Thread.objects.get(pk=thread)
    form_class = QuickReplyForm
    thread_name = thread.name

  
    return render(request, 'thread/viewthread.html',
                  {'thread': thread, 'posts': posts, 'thread_name': thread_name})

Post Model

class Post(models.Model):
    post_body = models.TextField(blank=True, null=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post_date = models.DateTimeField(auto_now_add=True)
    post_thread = models.ForeignKey(Thread, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.id) + ' | ' + str(self.author)

The User model is the standard Django model

As of now, if I want to access the post author in the template, I'd do this

{% for post in posts %}
         post.author
{% endfor %}

My question is, how do I access the tables of post.author. So if I want to filter how many posts that author has, I want to do something like user_posts = Post.objects.get(author=post.author). But that can't work in the views because "posts" is a queryset and not a value. How can I do this?

Upvotes: 0

Views: 179

Answers (1)

NKSM
NKSM

Reputation: 5884

In your template you can access your related objects with post_set:

{% for post in posts %}
    {{ post.author.post_set.count }}
{% endfor %}

If you need more then the total number of posts, do you want filter your related objects or something else. You can always write a custom method for your model. See Model methods

For example:

from django.utils.functional import cached_property


class Post(models.Model):
    post_body = models.TextField(blank=True, null=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    post_date = models.DateTimeField(auto_now_add=True)
    post_thread = models.ForeignKey(Thread, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.id) + ' | ' + str(self.author)

    @cached_property
    def count_by_author_and_thread(self):
        return self.author.post_set.filter(post_thread=self.post_thread).count()

And then in your template simple use:

{% for post in posts %}
    {{ post.count_by_author_and_thread }}
{% endfor %}

Upvotes: 2

Related Questions