U
U
user_of_toster2018-09-29 15:16:57
Django
user_of_toster, 2018-09-29 15:16:57

How Exclude works with OneToMany binding?

Let the application have the following models:

##models.py
from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    
    def __str__(self):
        return self.name


class Entry(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    headline = models.CharField(max_length=255)
    pub_date = models.DateField()
    
    def __str__(self):
        return self.headline

The code below returns all blogs that have at least one entry that matches the two conditions: headline__contains="lennon" and pub_date__year=2008.
Blog.objects.filter(entry__headline__contains='lennon', entry__pub_date__year=2008)

Question: Why can't the following code return all other blogs not filtered by the code above?
Blog.objects.exclude(entry__headline__contains="lennon", entry__pub_date__year=2008)

i.e. why the code above doesn't work like the code below
Blog.objects.exclude(entry__in=Entry.objects.filter(headline__contains="lennon", pub_date__year=2008))

Is this a flaw in the framework or a custom solution? How to use Exclude when filtering objects by attributes with ForeignKey()? What am I missing in understanding exclude?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Animkim, 2018-09-30
@user_of_toster

Exclude does not work as a filter on the contrary, more details in the doc:
https://docs.djangoproject.com/en/2.1/topics/db/qu...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question