Django:过滤相关对象,从结果中删除重复项 [英] Django: Filtering on the related object, removing duplicates from the result
本文介绍了Django:过滤相关对象,从结果中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定以下模型:
class Blog(models.Model):
name = models.CharField()
class Entry(models.Model):
blog = models.ForeignKey(Blog)
content = models.CharField()
我正在将以下内容传递给模板:
I am looking to pass the following to a template:
blogs = Blog.objects.filter(entry__content__contains = 'foo')
result = [(blog, blog.entry_set.filter(content__contains = 'foo'))
for blog in blogs]
render_to_response('my.tmpl', {'result': result}
但是,如果找到多个匹配的条目,Blog.objects.filter(...)返回相同的Blog对象多次。
However, "Blog.objects.filter(...)" returns the same Blog object multiple times if more than one matching entry is found.
如何删除重复项?或者更好的是,我错过了一个更简单的方法来将匹配列表传递给模板?
How do you remove the duplicates? Or better yet, am I missing a simpler way to pass the list of matches to the templates?
推荐答案
添加 .distinct()
将给你只有不同的结果。
Adding .distinct()
will give you only distinct results.
这篇关于Django:过滤相关对象,从结果中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文