Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django queryset with "isnull" argument returning duplicates

I want to only return items that don't have associated images. My relationship is something like this:

class Post(models.Model):
     ....fields


class Photo(models.Model):
    post=models.ForeignKey(Post,blank=True,null=True)
    photo=models.FileField(upload_to="pics")    


    def __unicode__(self):
        return str(self.post)

I put together the following query to return Post instances where Photo is not null:

    posts=Post.objects.filter(photo__photo__isnull=False)

The problem is that it's returning multiple copies of each Post instance per the number of Photo instances that are related to the Post instance. In other words, one post has 5 photos and it is therefore returning five copies in the queryset. I've looked through the documentation and this is a bit tricky. I ended up using distinct(), but I assume that I can make it work immediately.

Thanks

like image 752
Ben Avatar asked Jan 19 '23 19:01

Ben


2 Answers

To return posts that don't have associated photos, use the following query:

posts=Post.objects.filter(photo__isnull=True)

Later in your question you are using isnull=False. As you say, the resulting queryset will return each post once for every photo which is attached to it. To only include each post once in the queryset, use distinct.

posts=Post.objects.filter(photo__isnull=False).distinct()

I'm not sure why you query photo__photo__isnull in you're query -- My answer assumes you should use photo__isnull.

like image 184
Alasdair Avatar answered Jan 25 '23 16:01

Alasdair


I'm not sure what you mean by "but I assume that I can make it work immediately", but using either distinct(), or order_by() should be the solution to your problem.

like image 34
solartic Avatar answered Jan 25 '23 14:01

solartic