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
Although googletorp is right that you can't construct the query dynamically with a string, you can do it with dictionary parameters. Something like:
where mydict1 and 2 are of the form:
etc.
Something like this should work:
Edit: You can't create the query dynamically the same way you can construct a string containing a SQL statement to be executed when completed. If you want to do this, I would suggest using an if state, function or what suits your use case best:
This could be more complex, but I'm sure you get the idea.
This is a great way to do dynamic "OR" querying:
if you want to use "AND":
You can keep building your Q object in a somewhat dynamic fashion.
Example: