If I have the following two models:
class Blog(models.Model):
title = models.CharField(max_length=160)
text = models.TextField()
class Comment(models.Model):
blog = models.ForeignKey(Blog)
text = models.TextField()
As you can see, a Blog may have many Comments, but a Comment may only have one Blog.
How can I get all of the Blogs which only have Comments?
Thanks How
You can use Blog.objects.filter(comment__isnull=False)
this will return all blog instances has comment relation. You can also check comment__text__isnull=False
or anything you need to filter about comments. The SQL equivalent of the query above is: SELECT "app_blog"."id", "app_blog"."title", "app_blog"."text" FROM "app_blog" INNER JOIN "app_comment" ON ("app_blog"."id" = "app_comment"."blog_id") WHERE "app_comment"."id" IS NOT NULL
where app prefix is the name of django app
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.