Conteúdo do Curso
Django ORM Ninja: Advanced Techniques for Developers
Django ORM Ninja: Advanced Techniques for Developers
Q and F Objects
Django ORM extends its querying capabilities with more advanced features like F expressions and Q objects.
F Expressions
F expressions are used to refer to model field values directly in queries, enabling operations like comparisons and arithmetic directly in the database.
Example 1:
Updating the number of pages in all books by a certain percentage:
SQL-related query: (UPDATE Book SET pages = pages * 1.1;) This increases the page count of every book by 10%.
Example 2:
Suppose you want to identify books whose prices are significantly higher than the average price of books in their respective genres. You can use F expressions with comparisons to achieve this:
Q Objects
Q objects are used for complex query conditions, allowing the use of logical operators like AND/OR.
Example 1:
Finding books by a certain author OR in a certain genre:
This retrieves books either written by "J.K. Rowling" or in the "Fantasy" genre.
Example 2:
To find books that are not in the "fantasy" genre and have more than 300 pages, you can combine ~Q with an AND condition:
Note
The ~Q and ~F operators can be used to negate a query condition. For example, ~Q(author__name="J.K. Rowling") query fetches all books where the author is not "J.K. Rowling".
Obrigado pelo seu feedback!