Django QuerySet filter method returns multiple entries for one record
- by Yaroslav
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)