How to Filter a Django Query with a List of Values?

How to Filter a Django Query with a List of Values?

Let’s say you have a table called “contact_table” and you want to find all the rows having “id” in the list.

Here is how we can write SELECT SQL command for the same.

SELECT * FROM contact_table WHERE id=[2, 3, 6, 7, 8]

How can we achieve that the same in Django web development project?

Let’s see.

Filter a Django Query with a List of Values

Django has filter() method to filter out the query set.

Let’s say “Contact” model has field “id”. (By default it is autogenerated fields in the Django model). You can use any other field from the model.

Django has special __in operator that we can use with Django filter() method.

Contact.objects.filter(id__in=[2, 3, 6, 7, 8])

This will return query set from the model “Contact” after filtering a Django query with a list of values.

Filter Objects to Exclude id which is in a List

You can also write a query to exclude the filter object which has an id present in the list. For this, we are using exclude() method.

Contact.objects.filter().exclude(id__in=[2, 3, 6, 7, 8])

This will return all the contacts excluding which has an id not in the list.

Related Read:

Leave a Reply

Your email address will not be published. Required fields are marked *