简体   繁体   English

如何计算具有ForeignKey关系的对象数?

[英]How to count objects count that have ForeignKey relationship?

I have two tables, lets say: Blogs and Posts. 我有两个表,可以说:博客和帖子。 Posts have ForeignKey field which connects Blogs and Posts tables. 帖子具有ForeignKey字段,用于连接Blog和Posts表。

How can I count how many Blogs have at least 1 Post? 如何计算至少有1个帖子的博客数量?

排除没有帖子的博客,然后计数。

Blog.objects.exclude(post=None).count()

您可以按相关模型进行过滤

 Blog.objects.filter(post__isnull=False).count()

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

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