简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM