From an example you can see a multiple OR query filter:
Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
For example, this results in:
[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
However, I want to create this query filter from a list. How to do that?
e.g. [1, 2, 3] -> Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
easy..
from django.db.models import Q import you model args = (Q(visibility=1)|(Q(visibility=0)&Q(user=self.user))) #Tuple parameters={} #dic order = 'create_at' limit = 10
A shorter way of writing Dave Webb's answer using python's reduce function:
Another option I wasn't aware of until recently -
QuerySet
also overrides the&
,|
,~
, etc, operators. The other answers that OR Q objects are a better solution to this question, but for the sake of interest/argument, you can do:str(q.query)
will return one query with all the filters in theWHERE
clause.Maybe it's better to use sql IN statement.
See queryset api reference.
If you really need to make queries with dynamic logic, you can do something like this (ugly + not tested):
Using solution with
reduce
andor_
operator here how can you filter by multiply fields.p.s.
f
is a new format strings literal aded in python3.6In case we want to programmatically set what db field we want to query: