Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 294
knipknap Avatar asked Dec 30 '09 12:12

knipknap


1 Answers

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

like image 89
Ignacio Vazquez-Abrams Avatar answered Sep 25 '22 12:09

Ignacio Vazquez-Abrams