简体   繁体   English

Django通过关系统计外键

[英]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 = Forum.objects.get(slug=forum)

We can count the number of threads inside forum like this: forum.threads.count() 我们可以像这样计算论坛里面的线程数: 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. 我尝试过像all_posts = forum.thredas.posts.count()这样的东西,但正如预期的那样它没有用。

Thanks! 谢谢!

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. 通常在Django中,一个很好的原则是,当你想对模型做某事时,你应该从该模型开始查询。 So, since you need to count posts, you should start with the Post model. 所以,既然你需要计算帖子,你应该从Post模型开始。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM