Django's ORM works fine when your filters are combined using the AND operator. If you want to perform more complicated queries, you should use the Q function, which just gives you more flexibility with your logic.
- [Voiceover] In this video, we'll talk…about doing advanced queries.…To some people, this may mean writing raw SQL.…We won't be covering that here…because doing so causes us to lose…some of Django's benefits.…If you want to write SQL, then you'll want the raw function.…Sometimes you have something more complicated…that just doesn't work with a standard ORM.…For me, the most common problem…is when you want to use an OR condition.…I have good news for you.…Django makes this very easy.…Even though we can often get by…with a standard ORM syntax…and using the Q function feels a little scary,…you'll see that it works quite well.…
Use model.objects.filter…or model.objects.get just like you would normally,…but for the parameters, pass in one or more Q functions.…If you use more than one, they should be…either AND-ed or OR-ed together.…When you do that, the result is combined into one.…You can use parentheses to get the correct logic…if you want more complex operations.…Let's use an example.…In this case, I'm going to open a Django shell…
Django is one of the world's leading web development platforms. This Python web framework makes your app building experience smoother, faster, and easier. It is a key feature behind the success of many start-ups across the world, including Instagram and Nextdoor. This course introduces next-level advanced concepts to help you build your own professional-grade Django applications.
Author Kevin Veroneau starts off by explaining how class-based views—a powerful, but often poorly understood feature—work in Django. Then learn how to create custom middleware to help organize frequently used code. Have you ever wanted to build a complete RESTful API? Find out how to do just that, starting with a basic read-only API and then adding key-based authentication to allow the full range of CRUD functionality. Plus, discover how to use model managers and the Q method to make it easier to get the data we need to our views and clients.
For the finishing touches, dive into the details of caching to improve application performance, and then add custom management commands to help automate routine tasks.
- Extending class-based views
- Creating custom class-based views
- Managing your database with middleware
- Creating template filters and tags
- Building a RESTful API
- Modeling advanced database relationships and queries
- Using a model manager for your application