Django queryset with isnull argument returning duplicates

I only want to return elements that do not have related images. My relationship is as follows:

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 instances of Post where Photo is not null:

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

The problem is that it returns multiple instances of each Post instance for the number of Photo instances associated with the Post instance. In other words, one publication has 5 photos, and therefore it returns five instances in the query set. I looked through the documentation and it is a bit complicated. I ended up using distinct (), but I guess I can get it working immediately.

thank

+3
source share
2 answers

, , :

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

isnull=False. , . , .

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

, photo__photo__isnull - , photo__isnull.

+7

, " , ", distinct() order_by() .

+1

All Articles