问题
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