Django OR using Extra and Filter

I am trying to use Django ORM to generate a request using both advanced and filtering methods. Something like that:

Model.objects.filter(clauseA).extra(clauseB).all()

      

This generates a query, but the problem is that everything in the filter clause is AND and everything in the sub clause, so the sql looks like this:

SELECT * FROM model WHERE clauseA AND clauseB. 

      

My question is, is there a way to change the default combination operator for a query in Django so that the generated query is:

SELECT * FROM model WHERE clauseA OR clauseB. 

      

+3


source to share


2 answers


Try object Q

Model.objects.filter(Q(clauseA) | ~Q(clauseB))

      

EDIT



try it

Model.objects.filter(clauseA) | Model.objects.extra(clauseB)

      

+3


source


It might be easier if you just get rid of the filter clause and include that filter directly in the additional OR'd using a Postgres special function. I think this is already a limitation of the Django ORM.



However, you can try to create your own Func expression . Once you've created it for your Postgres specific function, you can use a combination of Func (), F () and Q () objects to get rid of that nasty .extra () function and nicely chaining them.

0


source







All Articles