Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Django ORM query using a mix of filter() and Q objects

I'm looking to create a slightly more complex query that is written fairly easily using raw SQL. Here's an example of the query in raw:

SELECT my,fields FROM sales WHERE is_paid = False OR status = 'toship' AND otherfield = 'FOO' AND anotherfield = 'BAR'

This is simple, it generates all the results that are is_paid = False and then a second result set for my AND matches.

Now I know about Q objects, I know about filtering but I can't seem to wrap my mind around how to achieve this in the Django ORM cleanly.

Any tips?

Thanks

like image 295
Bartek Avatar asked Nov 26 '22 22:11

Bartek


1 Answers

You can keep building your Q object in a somewhat dynamic fashion.

Example:

query1 = Q(is_paid=False)

query2 = Q()

if status:
    query2 = Q(status=status)

if otherfield:
    query2 = query2 & Q(otherfield=otherfield)

if anotherfield:
    query2 = query2 & Q(anotherfield=anotherfield)

query = query1 | query2

result = model.objects.filter(query)
like image 163
tarequeh Avatar answered Dec 05 '22 16:12

tarequeh