vincentf
vincentf

Reputation: 1499

How do I have multiple exclude conditions?

What is the correct way to do the following query:

sites = Site.objects.all().exclude(itempage__isnull=True or itempage__pk=1)

Upvotes: 2

Views: 4220

Answers (2)

Underoos
Underoos

Reputation: 5190

Just wanted to another way of achieving this. Just chain the conditions using exclude().

sites = Site.objects.all().exclude(itempage__isnull=True).exclude(itempage__pk=1)

Upvotes: 3

A. J. Parr
A. J. Parr

Reputation: 8026

I would recommend using Django's Q Objects to construct more complex queries.

from django.db.models import Q
Site.objects.exclude(Q(itempage__isnull=True) | Q(itempage__pk=q))

Q objects also support negation with the ~ operator like so:

from django.db.models import Q
Site.objects.filter(~Q(Q(itempage__isnull=True) | Q(itempage__pk=q)))

Upvotes: 7

Related Questions