我有三个看起来像这样的模型:
class Blog(models.Model):
name = models.CharField(max_length=100)
user = models.OneToOneField(User)
def __unicode__(self):
return self.name
class BlogPost(models.Model):
title = models.CharField(max_length=100)
blog = models.ForeignKey(Blog)
def __unicode__(self):
return self.title
class Stream(models.Model):
user = models.OneToOneField(User)
blog = models.ManyToManyField(Blog, blank=True)
def __unicode__(self):
return '%s' % self.user
在steam
对象中,我有两个blog
个对象。在第一个blog
对象中,我在第二个中有三个blogpost
是相同的。
然后我创建queryset:
stream = Stream.objects.get(pk=1)
blog = Blog.objects.filter(stream=stream)
print (blog)
<QuerySet [<Blog: Blog object>, <Blog: Blog object>]>
blogpost = BlogPost.objects.filter(blog=blog)
print (blogpost)
<QuerySet [<BlogPost: BlogPost object>, <BlogPost: BlogPost object>, <BlogPost: BlogPost object>]>
在blogpost
中,我只从第一个blog
个对象元素中获取,而不是从所有对象元素中获取。有人知道为什么会这样吗?
答案 0 :(得分:3)
您需要使用__in
查找
blog = Blog.objects.filter(stream=stream)
blogpost = BlogPost.objects.filter(blog__in=blog)