Django: Filtering on the related object, removing duplicates from the result

南笙酒味 提交于 2019-12-21 04:10:51

问题


Given the following models:

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}

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?


回答1:


Adding .distinct() will give you only distinct results.




回答2:


See the QuerySet API Docs for the "distinct()" function:

Returns a new QuerySet that uses SELECT DISTINCT in its SQL query. This eliminates duplicate rows from the query results.

By default, a QuerySet will not eliminate duplicate rows. In practice, this is rarely a problem, because simple queries such as Blog.objects.all() don't introduce the possibility of duplicate result rows. However, if your query spans multiple tables, it's possible to get duplicate results when a QuerySet is evaluated. That's when you'd use distinct().



来源:https://stackoverflow.com/questions/1979896/django-filtering-on-the-related-object-removing-duplicates-from-the-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!