intelis
intelis

Reputation: 8058

Django count foreign key through relation

I am building a simple forum application and I need some help with counting foreign key objects via through relation.

Let's say my models look like this:

class Forum(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField()
    slug = models.SlugField(unique=True, blank=True)

class Thread(models.Model):
    title = models.CharField(max_length=255)
    forum = models.ForeignKey(to=Forum, related_name='threads')
    slug = models.SlugField(unique=True, blank=True)

class Post(models.Model):
    body = models.TextField()
    author = models.ForeignKey(User)
    thread = models.ForeignKey(to=Thread,related_name='posts')

Now we create forum object.

forum = Forum.objects.get(slug=forum)

We can count the number of threads inside forum like this: forum.threads.count()

My question is, how can i count all the posts in a forum?

I've tried something like all_posts = forum.thredas.posts.count() but as expected it didn't work.

Thanks!

Upvotes: 1

Views: 265

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

Generally in Django it is a good principle that when you want to do something with a model, you should start your query from that model. So, since you need to count posts, you should start with the Post model.

From there you can use the double-underscore syntax to filter to the particular Forum you want.

forum_posts = Post.objects.filter(thread__forum=my_forum)
forum_post_count = forum_posts.count()

Upvotes: 4

Related Questions