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....];
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
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.
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.
.filter(id__in=[1, 3, 4, 5, 6....])
Read more about it at Django docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With