views:

29

answers:

2

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)
+1  A: 

Use distinct()

i.e.:
Blog.objects.filter(entries__title__contains='entry').distinct()

http://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct

Josh Wright
Thanks. I just didn't expected such behavior from the magical ORM :) The doc actually mentions this situation but I expected it to be described in section about querying related objects.
Yaroslav
+1  A: 

Use the distinct method

Blog.objects.filter(entries__title__contains='entry').distinct()
Eli Courtwright
+1 Thanks. Josh was the first who answered, accepting his answer.
Yaroslav