Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a django queryset using an array on a field like SQL's "IN"?

I'd like to filter a Django queryset using an array as a constraint on a field. AKA, my array, for example, a set of primary keys. I want to get only the objects that would be in that array, like the query in SQL would be:

SELECT * from table where id in [1,3,4,5,6....];
like image 737
mikec Avatar asked Oct 25 '10 16:10

mikec


People also ask

Can I filter a QuerySet Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

How can I filter a Django query with a list of values?

The sql query will be like SELECT * FROM mytable WHERE ids=[1, 3, 6, 7, 9] which is not true. You have to use in operator for this so you query will be like SELECT * FROM mytable WHERE ids in (1, 3, 6, 7, 9) for that Django provide __in operator.

How do I filter records in Django?

Django framework has a built-in filter() method to filter data from the database tables. A table can contain many records and sometimes determining some specific data are required based on the particular criteria. This task becomes easier by using the filter() method in different ways.


1 Answers

.filter(id__in=[1, 3, 4, 5, 6....])

Read more about it at Django docs.

like image 59
Ignacio Vazquez-Abrams Avatar answered Sep 25 '22 03:09

Ignacio Vazquez-Abrams