Conteúdo do Curso
Django ORM Ninja: Advanced Techniques for Developers
Django ORM Ninja: Advanced Techniques for Developers
Retrieve Query
We already know how to retrieve all instances using Author.objects.all()
. In this chapter, we'll learn how to obtain a specific instance or filter multiple instances based on certain attributes.
filter()
This query returns a new QuerySet containing objects that match the given lookup parameters. In our example, it will return only one Author with id=3.
The equivalent SQL command is SELECT * FROM Author WHERE last_name = 'Clear';
exclude()
Conversely, exclude()
returns a QuerySet with objects that do not match the specified parameters. Here, it will include all Authors whose last name isn't "Clear".
The equivalent SQL command is SELECT * FROM author WHERE last_name != 'Clear';
Combine filters
We can also combine filters. For instance, the query above demonstrates how to use multiple lookups, which we will explore more in the next sections.
The equivalent SQL command is SELECT * FROM author WHERE last_name LIKE 'C%' AND first_name != 'Ronald';
get()
To retrieve a specific object, we use the get method, where pk
is a "primary key", and it's the same as id
.
The equivalent SQL command is SELECT * FROM author WHERE id = 1;
Unlike get()
, slicing with filter()
doesn't raise an exception if there are no matching results; it simply returns an empty QuerySet.
Obrigado pelo seu feedback!