Django QuerySet 过滤方法为一条记录返回多个条目
尝试检索包含满足某些条件的条目的博客(请参阅下面的模型描述):
Blog.objects.filter(entries__title__contains='entry')
结果是:
[<Blog: blog1>, <Blog: blog1>]
由于执行 JOIN 来过滤相关模型上的对象,因此同一博客对象被检索两次。仅过滤唯一对象的正确语法是什么?
数据模型:
class Blog(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Entry(models.Model):
title = models.CharField(max_length=100)
blog = models.ForeignKey(Blog, related_name='entries')
def __unicode__(self):
return self.title
样本数据:
b1 = Blog.objects.create(name='blog1')
e1 = Entry.objects.create(title='entry 1', blog=b1)
e1 = Entry.objects.create(title='entry 2', blog=b1)
Trying to retrieve blogs (see model description below) that contain entries satisfying some criteria:
Blog.objects.filter(entries__title__contains='entry')
The results is:
[<Blog: blog1>, <Blog: blog1>]
The same blog object is retrieved twice because of JOIN performed to filter objects on related model. What is the right syntax for filtering only unique objects?
Data model:
class Blog(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Entry(models.Model):
title = models.CharField(max_length=100)
blog = models.ForeignKey(Blog, related_name='entries')
def __unicode__(self):
return self.title
Sample data:
b1 = Blog.objects.create(name='blog1')
e1 = Entry.objects.create(title='entry 1', blog=b1)
e1 = Entry.objects.create(title='entry 2', blog=b1)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用distinct()
即:
Blog.objects.filter(entries__title__contains='entry').distinct()
Use distinct()
i.e.:
Blog.objects.filter(entries__title__contains='entry').distinct()
http://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct
使用 distinct 方法
Use the distinct method