Django comes with excellent ORM - Object Relational Mapper for querying the database. It’s very good for most cases, but sometimes you need to handle more complex queries.
When you need to run complex queries, Django offers the Q Object.
When you need to retrieve something from the database you would use .filter() method.
|
|
This gives you all the posts whose title starts with “How to..”. What if you want to further filter the posts by another condition? That’s when Q Object comes in.
Q Object let’s you logically chain your queries.
Use & or , (AND) operators to search for more than 2 fields. Use | (OR) when looking for a value in at least one field.
|
|
With this chained query you retrieve posts whose title starts with How to and whose Topic name starts with Tutorial.
To return just unique values without duplicates you would append .distinct() at the end.
|
|
This is just a very basic example. You can do a lot more complex queries with Q Objects.