Diego Puente
Diego Puente

Reputation: 2004

django orm filter and exclude by related date field

models.py

class Model(models.Model):
    ...


class RelatedModel(models.Model):
    model = models.ForeignKey(Model, related_name="related_model")
    date = models.DateField()


I want to filter objects realted by a DateField by month and year.

any explanation?

thanks.


Answer from documentation:

Nota

The behavior of filter() for queries that span multi-value relationships, as described above, is not implemented equivalently for exclude(). Instead, the conditions in a single exclude() call will not necessarily refer to the same item.

For example, the following query would exclude blogs that contain both entries with «Lennon» in the headline and entries published in 2008:

Blog.objects.exclude( entry__headline__contains='Lennon', entry__pub_date__year=2008, )

However, unlike the behavior when using filter(), this will not limit blogs based on entries that satisfy both conditions. In order to do that, i.e. to select all blogs that do not contain entries published with «Lennon» that were published in 2008, you need to make two queries:

Blog.objects.exclude( entry__in=Entry.objects.filter( headline__contains='Lennon', pub_date__year=2008, ), )

Upvotes: 0

Views: 599

Answers (1)

iklinac
iklinac

Reputation: 15738

There is multiple RelatedModel instances for same Model where one of them could have month=6 and another one year=2021. Exclude will also eliminate these

As documented you will have to filter exactly instances with both conditions

Model.objects.exclude(
    related_model__in=RelatedModel.objects.filter(
        related_model__date__month=6,
        related_model__date__year=2021,
    ),
)

Upvotes: 2

Related Questions