blackwindow
blackwindow

Reputation: 437

How to add multiple filters in django query set

I have a query set

queryset = Record.objects.filter(type__icontains='28').exclude..............

I want to add some other types also to my filter like type__icontains='28' , type__icontains='14', type__icontains='20' etc.

How can I do that? Please help

Upvotes: 1

Views: 5715

Answers (1)

Matt Seymour
Matt Seymour

Reputation: 9395

You have two options you will need to decide which one you use as your question is not very complete.

IN syntax

This is basically stating select values where <attribute> IN <set>

result = SomeModel.objects.filter(id__in=[28,14,20])

# same as
SELECT * FROM SomeModel WHERE SomeModel.id IN (28,14,20)

Q Objects

You will need to use Q objects. They allow for complex data queries. The good news is once you have read the django docs (its really complete) you should be able to implement them easily into your code.

In your question you have not stated if you are trying to do an AND or OR. Just as a starting point you can do the following:

# AND
Q(type_icontains=28) & Q(type_icontains=14)

# OR
Q(type_icontains=28) | Q(type_icontains=14)

Upvotes: 4

Related Questions