示例代码
class Person(models.Model):
name = models.CharField(max_length=100)
class Post(models.Model):
author = models.ForeignKey(Person)
content = models.TextField()
class Comment(models.Model):
post = models.ForeignKey(Post)
author = models.ForeignKey(Person)
content = models.TextField()
foo = Person.objects.create(name='foo')
bar = Person.objects.create(name='bar')
blog = Post.objects.create(author=foo,content='Random Blog 1')
blog2 = Post.objects.create(author=foo, content='Radom Blog 2')
c1 = Comment.objects.create(post=blog, author=foo, content='Comment on blog1')
c2 = Comment.objects.create(post=blog, author=bar, content='Bar comment on blog1')
c3 = Comment.objects.create(post=blog2, author=foo, content='Comment on blog2')
c4 = Comment.objects.create(post=blog2, author=bar, content='Bar comment on blog2')
如何创建一个返回所有Post的作者foo的查询,并且每个Post的comment_set中的Comment仅由foo创建。
答案 0 :(得分:0)
我可能会这样做:
from django.db.models import Count, F
Post.objects.filter(author=foo
).annotate(comment_count=Count('comment_set')
).filter(comment_set__author=foo #
).annotate(foo_comment_count=Count('comment_set')
).filter(foo_comment_count=F('comment_count')))
另一种方法是子查询,选择由其他人评论的帖子然后foo
,然后选择所有不在该组中的PK。
使用Django的ORM编写查询与编写SQL查询没有太大区别。作为最后的手段,您总是可以写一个raw query。