---
title: "Fazendo consultas"
version: 4.2
locale: pt-br
source: https://docs.djangoproject.com/pt-br/4.2/topics/db/queries/
canonical: https://djangodocs.dev/pt-br/4.2/topics/db/queries/
---
# Fazendo consultas

Uma vez que tenha criado seu [modelos de dados](/pt-br/4.2/topics/db/models/), o Django automaticamente lhe dá uma API de abstração do banco de dados que deixa que crie, retorne, edite e delete objetos. Este documento explica como usar essa API. Refira-se a [Referência de modelo de dados](/pt-br/4.2/ref/models/) para detalhes completos de todos os vários modelos de opções de filtros.

Throughout this guide (and in the reference), we’ll refer to the following
models, which comprise a blog application:

```python
from datetime import date

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __str__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=200)
    email = models.EmailField()

    def __str__(self):
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField(default=date.today)
    authors = models.ManyToManyField(Author)
    number_of_comments = models.IntegerField(default=0)
    number_of_pingbacks = models.IntegerField(default=0)
    rating = models.IntegerField(default=5)

    def __str__(self):
        return self.headline
```

## Criando objetos

Para representar uma tabela de banco de dados em objetos Python, o Django usa um sistema intuitivo: Uma classe de modelo que representa uma tabela de banco de dados, e uma intância desta classe representa um registro particular em uma tabela de banco de dados.

Para criar um objeto, instancie-o usando argumentos nomeados para a classe de modelo, então chame o [`save()`](/pt-br/4.2/ref/models/instances/#django.db.models.Model.save) para persistí-lo no banco de dados.

Assuming models live in a file `mysite/blog/models.py`, here’s an example:

```pycon
>>> from blog.models import Blog
>>> b = Blog(name="Beatles Blog", tagline="All the latest Beatles news.")
>>> b.save()
```

Este executa um comando SQL `INSERT` por detrás dos panos. O Django não acessa o banco de dados até que você chame explicitamente o [`save()`](/pt-br/4.2/ref/models/instances/#django.db.models.Model.save).

O método [`save()`](/pt-br/4.2/ref/models/instances/#django.db.models.Model.save) não retorna um valor .

> **See also**
>
> O [`save()`](/pt-br/4.2/ref/models/instances/#django.db.models.Model.save) recebe várias opções avançadas não descritas aqui. Veja a documentacão em [`save()`](/pt-br/4.2/ref/models/instances/#django.db.models.Model.save) para detalhes completos.
>
> Para criar e salvar um objeto em um único passo, use o método [`create()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.create).

## Salvando alterações para objetos

Para salvar as alerações para um objeto que já existe no banco de dados, use o [`save()`](/pt-br/4.2/ref/models/instances/#django.db.models.Model.save).

Given a `Blog` instance `b5` that has already been saved to the database,
this example changes its name and updates its record in the database:

```pycon
>>> b5.name = "New name"
>>> b5.save()
```

Isso executa um comando SQL `UPDATE` por detras dos panos. o Django não acessa o banco de dados até que você explicitamente chame o [`save()`](/pt-br/4.2/ref/models/instances/#django.db.models.Model.save).

### Salvando campos `ForeignKey` e `ManyToManyField`

Updating a [`ForeignKey`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey) field works exactly the same
way as saving a normal field – assign an object of the right type to the field
in question. This example updates the `blog` attribute of an `Entry`
instance `entry`, assuming appropriate instances of `Entry` and `Blog`
are already saved to the database (so we can retrieve them below):

```pycon
>>> from blog.models import Blog, Entry
>>> entry = Entry.objects.get(pk=1)
>>> cheese_blog = Blog.objects.get(name="Cheddar Talk")
>>> entry.blog = cheese_blog
>>> entry.save()
```

Updating a [`ManyToManyField`](/pt-br/4.2/ref/models/fields/#django.db.models.ManyToManyField) works a little
differently – use the
[`add()`](/pt-br/4.2/ref/models/relations/#django.db.models.fields.related.RelatedManager.add) method on the field
to add a record to the relation. This example adds the `Author` instance
`joe` to the `entry` object:

```pycon
>>> from blog.models import Author
>>> joe = Author.objects.create(name="Joe")
>>> entry.authors.add(joe)
```

To add multiple records to a [`ManyToManyField`](/pt-br/4.2/ref/models/fields/#django.db.models.ManyToManyField) in one
go, include multiple arguments in the call to
[`add()`](/pt-br/4.2/ref/models/relations/#django.db.models.fields.related.RelatedManager.add), like this:

```pycon
>>> john = Author.objects.create(name="John")
>>> paul = Author.objects.create(name="Paul")
>>> george = Author.objects.create(name="George")
>>> ringo = Author.objects.create(name="Ringo")
>>> entry.authors.add(john, paul, george, ringo)
```

O Django irá reclamar se você tentar assinalar ou adicionar um objeto do tipo errado.

## Recuperando objetos

Para recuperar objetos do seu banco de dados, construa uma  [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) através da [`Manager`](/pt-br/4.2/topics/db/managers/#django.db.models.Manager) na sua classe de modelo.

A [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) representa uma coleção de objetos do seu banco de dados. Ele pode ter zero, um ou muitos \* filtros\*. Filtros  limitam os resultados baseado nos parâmetros dados. Em termos de SQL, um [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet)  equivale a um comando `SELECT`, e um filtro é um clásula limitante tal como `WHERE` or `LIMIT`.

You get a [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) by using your model’s
[`Manager`](/pt-br/4.2/topics/db/managers/#django.db.models.Manager). Each model has at least one
[`Manager`](/pt-br/4.2/topics/db/managers/#django.db.models.Manager), and it’s called
[`objects`](/pt-br/4.2/ref/models/class/#django.db.models.Model.objects) by default. Access it directly via the
model class, like so:

```pycon
>>> Blog.objects
<django.db.models.manager.Manager object at ...>
>>> b = Blog(name="Foo", tagline="Bar")
>>> b.objects
Traceback:
    ...
AttributeError: "Manager isn't accessible via Blog instances."
```

> **Note**
>
> Os `Managers` são acessíveis somente através das classes de modelo, e não de instâncias de modelos, para reforçar a separação entre operações no “nível das tabelas” e operações no “nível dos registros”.

A [`Manager`](/pt-br/4.2/topics/db/managers/#django.db.models.Manager) é a principal fonte de `QuerySets` para um modelo.  Por exemplo, `Blog.objects.all()` retorna uma [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet)  que contém todos os objetos do tipo `Blog` do banco de dados.

### Recuperando todos os objetos

The simplest way to retrieve objects from a table is to get all of them. To do
this, use the [`all()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.all) method on a
[`Manager`](/pt-br/4.2/topics/db/managers/#django.db.models.Manager):

```pycon
>>> all_entries = Entry.objects.all()
```

O método [`all()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.all) retorna uma [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) de todos os objetos do banco de dados.

### Recuperando objetos específicos com filtros.

A [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) retornada pelo [`all()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.all) descreve todos os objetos da tabela do banco de dados. Em geral, porém, você precisa selecionar somente um subconjunto de todo o conjunto de objetos.

Para criar o subconjunto, você refina o [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) inicial, adicionando filtros de condições. As duas maneiras mais comuns de refinar um [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) são:

**`filter(**kwargs)`**

  Retorna uma nova [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) contendo objetos que combinem com os parâmetros de filtros dados.

**`exclude(**kwargs)`**

  Retornam uma nova [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet)  contendo objetos que *não* combinem com os parâmetros de filtros dados.

Os parâmetros de filtros (`**kwargs` nas definições da função acima) devem estar no formato descrito em [Filtros de campo](#field-lookups) abaixo.

Prr exemplo, para ter um [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) de entradas de blog do ano 2006, use o [`filter()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.filter) como aqui:

```
Entry.objects.filter(pub_date__year=2006)
```

Com a classe “manager” padrão, é o mesmo que:

```
Entry.objects.all().filter(pub_date__year=2006)
```

#### Filtros encadeados

The result of refining a [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) is itself a
[`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet), so it’s possible to chain
refinements together. For example:

```pycon
>>> Entry.objects.filter(headline__startswith="What").exclude(
...     pub_date__gte=datetime.date.today()
... ).filter(pub_date__gte=datetime.date(2005, 1, 30))
```

Ele pega o [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) inicial com todas as entradas do banco de dados, adiciona um filtro, então adiciona uma exclusão, então outro filtro. O resultado final é um [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) contendo todas as entradas com uma manchete que comece com “What”, que foi publicada entre 30 de janeiro de 2005 e o dia de hoje.

#### `QuerySet`s filtradas são únicas

Cada vez que refine um [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet), você tem uma nova [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) que não está de forma alguma vinculada ao anterior [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet). Cada refinamento cria uma [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) separada e distinta que pode ser armazenada, usada e resusada.

Example:

```pycon
>>> q1 = Entry.objects.filter(headline__startswith="What")
>>> q2 = q1.exclude(pub_date__gte=datetime.date.today())
>>> q3 = q1.filter(pub_date__gte=datetime.date.today())
```

Estes três `QuerySets` são separados. O primeiro é um [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) básico contendo todas as entradas que contenham uma manchete iniciando com “What”. O segundo é um subconjunto do primeiro, com um critério adicional que exclui aqueles cujo o `pub_date` é hoje ou está no futuro. O terceiro é também um subconjunto do primeiro, com um critério adicional que seleciona somente os registros cujo o `pub_date` é hoje ou está no futuro. A [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) (`q1`) inicial não é afetado pelo processo de refinamento.

#### `QuerySet`s são “lazy”

`QuerySets` are lazy – the act of creating a
[`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) doesn’t involve any database
activity. You can stack filters together all day long, and Django won’t
actually run the query until the [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) is
*evaluated*. Take a look at this example:

```pycon
>>> q = Entry.objects.filter(headline__startswith="What")
>>> q = q.filter(pub_date__lte=datetime.date.today())
>>> q = q.exclude(body_text__icontains="food")
>>> print(q)
```

Apesar de parece que isso seja três acessos ao banco de dados, de fato ele acessa o banco de dados somente um vez, na última linha (`print(q)`). Em geral, os resultados de uma [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) não são buscados no banco de dados até que você “peça” por eles. Quando fizer, a [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) é *interpretada* acessando o banco de dados. Para mais detalhes de quando exatamente a interpretação ocorre, veja [When QuerySets are evaluated](/pt-br/4.2/ref/models/querysets/#when-querysets-are-evaluated).

### Recuperando um único objeto com `get()`

O [`filter()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.filter) sempre lhe dará um [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet), mesmo se um único objeto combina com a consulta - neste caso, ele será uma [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) que contém um único elemento.

If you know there is only one object that matches your query, you can use the
[`get()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.get) method on a
[`Manager`](/pt-br/4.2/topics/db/managers/#django.db.models.Manager) which returns the object directly:

```pycon
>>> one_entry = Entry.objects.get(pk=1)
```

Você pode usar qualquer expressão de consulta com [`get()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.get), tal como com [`filter()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.filter) \- denovo, veja o [Campos de consulta](#field-lookups) abaixo.

Note que existe uma diferença entre usar o [`get()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.get), e usar o [`filter()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.filter) com uma fatia de `[0]`. Se não houver resultados que combinem com a consulta, o  [`get()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.get) irá emitir uma exceção `DoesNotExist`. Esta exceção é um atributo da classe de modelo na qual a consulta está sendo realizada - no código acima, se não houver objeto `Entry` com a chave-primária de 1, o Django irá emitir um `Entry.DoesNotExist`.

De maneira similar, o Django irá reclamar se mais de um item combinar com a consulta [`get()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.get). Neste caso, ele emitirá um [`MultipleObjectsReturned`](/pt-br/4.2/ref/exceptions/#django.core.exceptions.MultipleObjectsReturned), o qual denovo é ele próprio um atributo da classe de modelo.

### Outros `QuerySet` métodos

Na maioria das vezes você usará o [`all()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.all), [`get()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.get), [`filter()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.filter) e o [`exclude()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.exclude) quando precisar buscar objetos no banco de dados. Porém, está longe do todo que existe; veja the a [Refrêcia da API de QuerySet](/pt-br/4.2/ref/models/querysets/#queryset-api) para uma lista completa das vários métodos da [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet).

### Limitando `QuerySet`s

Use um subconjunto da syntax de fatias de array Python para limitar seu [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) para um certo número de resultados. Este é o equivalente às cláusulas SQL `Limit` e `OFFSET`.

For example, this returns the first 5 objects (`LIMIT 5`):

```pycon
>>> Entry.objects.all()[:5]
```

This returns the sixth through tenth objects (`OFFSET 5 LIMIT 5`):

```pycon
>>> Entry.objects.all()[5:10]
```

Índice negativo (isto é `Entry.objects.all()[-1]`) não é suportado.

Generally, slicing a [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) returns a new
[`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) – it doesn’t evaluate the query. An
exception is if you use the “step” parameter of Python slice syntax. For
example, this would actually execute the query in order to return a list of
every *second* object of the first 10:

```pycon
>>> Entry.objects.all()[:10:2]
```

Further filtering or ordering of a sliced queryset is prohibited due to the
ambiguous nature of how that might work.

To retrieve a *single* object rather than a list
(e.g. `SELECT foo FROM bar LIMIT 1`), use an index instead of a slice. For
example, this returns the first `Entry` in the database, after ordering
entries alphabetically by headline:

```pycon
>>> Entry.objects.order_by("headline")[0]
```

This is roughly equivalent to:

```pycon
>>> Entry.objects.order_by("headline")[0:1].get()
```

Note, porém, que o primeiro irá emitir um `IndexError` enquanto o segundo emitirá um `DoesNotExist` se nenhum objeto combinar com o critério dado. Veja o [`get()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.get) para mais detalhes.

### Filtros de campo

Filtros de campo é o que você usa para especiíicar os parâmetros da cláusula `WHERE`. Eles são especificados como argumentos nomeados para os métodos da  [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet):  [`filter()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.filter), [`exclude()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.exclude) e [`get()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.get).

Basic lookups keyword arguments take the form `field__lookuptype=value`.
(That’s a double-underscore). For example:

```pycon
>>> Entry.objects.filter(pub_date__lte="2006-01-01")
```

Traduzido (groseiramente) no seguinte SQL:

```sql
SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';
```

> **Como isso é possível**
>
> Python has the ability to define functions that accept arbitrary name-value
> arguments whose names and values are evaluated at runtime. For more
> information, see [Keyword Arguments](https://docs.python.org/3/tutorial/controlflow.html#tut-keywordargs) in the official Python tutorial.

O campo especificado em um filtro tem que ser um nome de campoo do modelo. Existe uma exceção porém, no caso de uma [`ForeignKey`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey) você pode especificar o nome do campo com um sufixo `_id`. Neste caso, é esperado que o valor do parâmetro contenha literalmente o valor da chave-primária do modelo estrageiro. Por exemplo:

```
>>> Entry.objects.filter(blog_id=4)
```

Se você passar um argumento nomeado inválido, a funçao do filtro irá emitir um `TypeError`.

The database API supports about two dozen lookup types; a complete reference
can be found in the [field lookup reference](/pt-br/4.2/ref/models/querysets/#field-lookups). To give you
a taste of what’s available, here’s some of the more common lookups you’ll
probably use:

**[`exact`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-exact)**

  An “exact” match. For example:

  ```pycon
  >>> Entry.objects.get(headline__exact="Cat bites dog")
  ```

  Geraria SQL ao longo destas linhas:

  ```sql
  SELECT ... WHERE headline = 'Cat bites dog';
  ```

  Se você não fornecer um tipo de filtro – isto é, se o seu argumento nomeado não contiver um “underscore” duplo – o tipo de filtro é assumido como sendo `exact`

  For example, the following two statements are equivalent:

  ```pycon
  >>> Blog.objects.get(id__exact=14)  # Explicit form
  >>> Blog.objects.get(id=14)  # __exact is implied
  ```

  Isso se dá por conveniência, porque os filtros `exact` são casos comuns.

**[`iexact`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-iexact)**

  A case-insensitive match. So, the query:

  ```pycon
  >>> Blog.objects.get(name__iexact="beatles blog")
  ```

  Deveria encontrar um `Blog` entitulado `"Beatles Blog"`, `"beatles blog"`, ou mesmo `"BeAtlES blOG"`.

**[`contains`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-contains)**

  Teste de contenção sensíveis ao tipo de caixa. Por exemplo:

  ```
  Entry.objects.get(headline__contains="Lennon")
  ```

  Mais ou menos traduzido para este SQL:

  ```sql
  SELECT ... WHERE headline LIKE '%Lennon%';
  ```

  Note que este irá encontrar o “headline” `'Today Lennon honored'` mas não o `'today lennon honored'`.

  Existe também uma versão que ignora o tipo de caixa, [`icontains`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-icontains).

**[`startswith`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-startswith), [`endswith`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-endswith)**

  Busca começa-com e termina-com, respectivamente. Existe também a versão que ignora o tipo de caixa chamada [`istartswith`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-istartswith) e [`iendswith`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-iendswith).

Denovo, isso aqui somente arranha a superfície. Uma refrência completa pode ser achada na [Referência de filtros de campo](/pt-br/4.2/ref/models/querysets/#field-lookups).

### Filtros que abrangem os relacionamentos

Django offers a powerful and intuitive way to “follow” relationships in
lookups, taking care of the SQL `JOIN`s for you automatically, behind the
scenes. To span a relationship, use the field name of related fields
across models, separated by double underscores, until you get to the field you
want.

This example retrieves all `Entry` objects with a `Blog` whose `name`
is `'Beatles Blog'`:

```pycon
>>> Entry.objects.filter(blog__name="Beatles Blog")
```

A abrangância pode ser tão profunda quanto queira.

It works backwards, too. While it [`can be customized`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey.related_query_name), by default you refer to a “reverse”
relationship in a lookup using the lowercase name of the model.

This example retrieves all `Blog` objects which have at least one `Entry`
whose `headline` contains `'Lennon'`:

```pycon
>>> Blog.objects.filter(entry__headline__contains="Lennon")
```

Se você estiver filtrando através de múltiplos relacionamentos e um dos modelos intermediários não tiver um valor que vá de encontro com a condição do filtro, o Django irá tratá-lo como se houvesse um objeto vazio (todos os valores são `NULL`), mas válido. Tudo isso significa que nenhum erro será emitido. Por exemplo, neste filtro:

```
Blog.objects.filter(entry__authors__name="Lennon")
```

(se houvesse um modelo `Author` relacionado), se não houvesse  `author` associado com uma “entry”, seria tratado como se também não houvesse um `name` anexo, ao invés de emitir um erro por causa do `author` faltante.

```
Blog.objects.filter(entry__authors__name__isnull=True)
```

irá retornar objeto do tipo `Blog` que tenham um `name` vazio no `author` a também aqueles os quais tem um `author` vazio no `entry`.  Se você não que estes últimos objetos, você poderia escrever:

```
Blog.objects.filter(entry__authors__isnull=False, entry__authors__name__isnull=True)
```

#### Abrangendo relacionamentos multi-interpretados

When spanning a [`ManyToManyField`](/pt-br/4.2/ref/models/fields/#django.db.models.ManyToManyField) or a reverse
[`ForeignKey`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey) (such as from `Blog` to `Entry`),
filtering on multiple attributes raises the question of whether to require each
attribute to coincide in the same related object. We might seek blogs that have
an entry from 2008 with *“Lennon”* in its headline, or we might seek blogs that
merely have any entry from 2008 as well as some newer or older entry with
*“Lennon”* in its headline.

To select all blogs containing at least one entry from 2008 having *“Lennon”*
in its headline (the same entry satisfying both conditions), we would write:

```
Blog.objects.filter(entry__headline__contains="Lennon", entry__pub_date__year=2008)
```

Otherwise, to perform a more permissive query selecting any blogs with merely
*some* entry with *“Lennon”* in its headline and *some* entry from 2008, we
would write:

```
Blog.objects.filter(entry__headline__contains="Lennon").filter(
    entry__pub_date__year=2008
)
```

Suppose there is only one blog that has both entries containing *“Lennon”* and
entries from 2008, but that none of the entries from 2008 contained *“Lennon”*.
The first query would not return any blogs, but the second query would return
that one blog. (This is because the entries selected by the second filter may
or may not be the same as the entries in the first filter. We are filtering the
`Blog` items with each filter statement, not the `Entry` items.) In short,
if each condition needs to match the same related object, then each should be
contained in a single [`filter()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.filter) call.

> **Note**
>
> As the second (more permissive) query chains multiple filters, it performs
> multiple joins to the primary model, potentially yielding duplicates.
>
> ```
> >>> from datetime import date
> >>> beatles = Blog.objects.create(name='Beatles Blog')
> >>> pop = Blog.objects.create(name='Pop Music Blog')
> >>> Entry.objects.create(
> ...     blog=beatles,
> ...     headline='New Lennon Biography',
> ...     pub_date=date(2008, 6, 1),
> ... )
> <Entry: New Lennon Biography>
> >>> Entry.objects.create(
> ...     blog=beatles,
> ...     headline='New Lennon Biography in Paperback',
> ...     pub_date=date(2009, 6, 1),
> ... )
> <Entry: New Lennon Biography in Paperback>
> >>> Entry.objects.create(
> ...     blog=pop,
> ...     headline='Best Albums of 2008',
> ...     pub_date=date(2008, 12, 15),
> ... )
> <Entry: Best Albums of 2008>
> >>> Entry.objects.create(
> ...     blog=pop,
> ...     headline='Lennon Would Have Loved Hip Hop',
> ...     pub_date=date(2020, 4, 1),
> ... )
> <Entry: Lennon Would Have Loved Hip Hop>
> >>> Blog.objects.filter(
> ...     entry__headline__contains='Lennon',
> ...     entry__pub_date__year=2008,
> ... )
> <QuerySet [<Blog: Beatles Blog>]>
> >>> Blog.objects.filter(
> ...     entry__headline__contains='Lennon',
> ... ).filter(
> ...     entry__pub_date__year=2008,
> ... )
> <QuerySet [<Blog: Beatles Blog>, <Blog: Beatles Blog>, <Blog: Pop Music Blog]>
> ```

> **Note**
>
> O comportamento do [`filter()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.filter) para consultas que abrangem relacionamentos com valores múltiplos, como descrito acima, não é implementado de maneira equivalente no [`exclude()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.exclude). Ao invés, as condições em uma única chamada [`exclude()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.exclude) não necessariamente irão se referenciar ao mesmo item.
>
> Por exemplo, a seguinte consulta excluiria blogs que contém *ambas* “entries” com *“Lennon”*  na manchete *e* “entries” publicadas em 2008:
>
> ```
> Blog.objects.exclude(
>     entry__headline__contains="Lennon",
>     entry__pub_date__year=2008,
> )
> ```
>
> Contudo, diferente do comportamento quando usado o [`filter()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.filter), este não limitará blogs baseados em “entries” que satisfaçam ambas as condições. Para tal, isto é, para selecionar todos os blogs que não contenham “entries” publicadas com *“Lennon”* que foram publicadas em 2008, você precisa fazer duas consultas:
>
> ```
> Blog.objects.exclude(
>     entry__in=Entry.objects.filter(
>         headline__contains="Lennon",
>         pub_date__year=2008,
>     ),
> )
> ```

### Filtros podem referenciar campos do modelo

Nos exemplos dados até agora, construímos filtros que comparam o valor de um campo de modelo com uma constante. Mas e se você quiser comparar o valor de um modelo com outro campo no mesmo modelo?

O Django fornece a [`F expressions`](/pt-br/4.2/ref/models/expressions/#django.db.models.F) para permitir tais comparações. Instâncias de `F()` atuam como uma referência a um campo de modelo dentro de uma consulta. Essas referências podem então ser comparadas a valores de dois diferentes campos na mesma instância de modelo.

For example, to find a list of all blog entries that have had more comments
than pingbacks, we construct an `F()` object to reference the pingback count,
and use that `F()` object in the query:

```pycon
>>> from django.db.models import F
>>> Entry.objects.filter(number_of_comments__gt=F("number_of_pingbacks"))
```

Django supports the use of addition, subtraction, multiplication,
division, modulo, and power arithmetic with `F()` objects, both with constants
and with other `F()` objects. To find all the blog entries with more than
*twice* as many comments as pingbacks, we modify the query:

```pycon
>>> Entry.objects.filter(number_of_comments__gt=F("number_of_pingbacks") * 2)
```

To find all the entries where the rating of the entry is less than the
sum of the pingback count and comment count, we would issue the
query:

```pycon
>>> Entry.objects.filter(rating__lt=F("number_of_comments") + F("number_of_pingbacks"))
```

You can also use the double underscore notation to span relationships in
an `F()` object. An `F()` object with a double underscore will introduce
any joins needed to access the related object. For example, to retrieve all
the entries where the author’s name is the same as the blog name, we could
issue the query:

```pycon
>>> Entry.objects.filter(authors__name=F("blog__name"))
```

For date and date/time fields, you can add or subtract a
[`timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta) object. The following would return all entries
that were modified more than 3 days after they were published:

```pycon
>>> from datetime import timedelta
>>> Entry.objects.filter(mod_date__gt=F("pub_date") + timedelta(days=3))
```

The `F()` objects support bitwise operations by `.bitand()`, `.bitor()`,
`.bitxor()`, `.bitrightshift()`, and `.bitleftshift()`. For example:

```pycon
>>> F("somefield").bitand(16)
```

> **Oracle**
>
> Oracle doesn’t support bitwise XOR operation.

### Expressions can reference transforms

Django supports using transforms in expressions.

For example, to find all `Entry` objects published in the same year as they
were last modified:

```pycon
>>> from django.db.models import F
>>> Entry.objects.filter(pub_date__year=F("mod_date__year"))
```

To find the earliest year an entry was published, we can issue the query:

```pycon
>>> from django.db.models import Min
>>> Entry.objects.aggregate(first_published_year=Min("pub_date__year"))
```

This example finds the value of the highest rated entry and the total number
of comments on all entries for each year:

```pycon
>>> from django.db.models import OuterRef, Subquery, Sum
>>> Entry.objects.values("pub_date__year").annotate(
...     top_rating=Subquery(
...         Entry.objects.filter(
...             pub_date__year=OuterRef("pub_date__year"),
...         )
...         .order_by("-rating")
...         .values("rating")[:1]
...     ),
...     total_comments=Sum("number_of_comments"),
... )
```

### O atalho de filtro `pk`

Por conveniência, o Django fornece um atalho para o filtro `pk`, o que representa a “chave-primária”.

In the example `Blog` model, the primary key is the `id` field, so these
three statements are equivalent:

```pycon
>>> Blog.objects.get(id__exact=14)  # Explicit form
>>> Blog.objects.get(id=14)  # __exact is implied
>>> Blog.objects.get(pk=14)  # pk implies id__exact
```

The use of `pk` isn’t limited to `__exact` queries – any query term
can be combined with `pk` to perform a query on the primary key of a model:

```pycon
# Get blogs entries with id 1, 4 and 7
>>> Blog.objects.filter(pk__in=[1, 4, 7])

# Get all blog entries with id > 14
>>> Blog.objects.filter(pk__gt=14)
```

`pk` lookups also work across joins. For example, these three statements are
equivalent:

```pycon
>>> Entry.objects.filter(blog__id__exact=3)  # Explicit form
>>> Entry.objects.filter(blog__id=3)  # __exact is implied
>>> Entry.objects.filter(blog__pk=3)  # __pk implies __id__exact
```

### Substituição de sinais de porcentagem e “underscores” nos comandos `Like`

Os campos filtros que equivalem ao comando SQL `LIKE` (`iexact`, `contains`, `icontains`, `startswith`, `istartswith`, `endswith` and `iendswith`) irão automaticamente substituir os dois caracteres especiais usados em comandos `LIKE` – o sinal de porcentagem e o “underscore”.  (Em um comando `LIKE`, o sinal de porcentagem significa múltiplos-caracteres curingas e o “underscore” siginifica um único caracter curinga.)

This means things should work intuitively, so the abstraction doesn’t leak.
For example, to retrieve all the entries that contain a percent sign, use the
percent sign as any other character:

```pycon
>>> Entry.objects.filter(headline__contains="%")
```

O Django irá cuidar da citação por você; o SQL resultante se parecerá com algo como:

```sql
SELECT ... WHERE headline LIKE '%\%%';
```

O mesmo vale para os “underscores”. Ambos os sinais, porcentagem e “underscores”, são manipulados para você de maneira transparente.

### “Cache”  e `QuerySets`s

Cada [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) contém um “cache” para minimizar o acesso ao banco de dados. Entendendo como isso funciona lhe permitirá escrever código mais eficiente.

Em uma classe [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) que acaba de ser criada, o “cache” está vazio. A primeira vez que a [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) é interpretada – e portanto, uma consulta ao banco acontece – o Django salva o resultado da consulta no  “cache” da [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet)’s e retorna o resultado que foi requerido explicitamente (exemplo, o próximo elemento, se o [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) está sendo iterado). Execuçãoes subsequentes do [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) reusam os resultados que estão no “cache”.

Keep this caching behavior in mind, because it may bite you if you don’t use
your [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet)s correctly. For example, the
following will create two [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet)s, evaluate
them, and throw them away:

```pycon
>>> print([e.headline for e in Entry.objects.all()])
>>> print([e.pub_date for e in Entry.objects.all()])
```

Isso significa que a mesma consulta de banco de dados será executada duas vezes, efetivamente dobrando a carga no banco de dados. Também existe a posibilidade das duas listas não incluírem os mesmos registros de banco de dados, porque uma `Entry` talvez tenha sido adicionada ou deletada durante a fração de segundo entre as duas requisições.

To avoid this problem, save the [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) and
reuse it:

```pycon
>>> queryset = Entry.objects.all()
>>> print([p.headline for p in queryset])  # Evaluate the query set.
>>> print([p.pub_date for p in queryset])  # Reuse the cache from the evaluation.
```

#### Quando `QuerySet`s não são armazenados no “cache”

Resultados de consultas nem sempre são salvas no “cache”. Quando interpretar somente *parte*  da consulta, o “cache” é veririficado, mas se ele não estiver populado então os itens retornados pela consulta subsequente não vão para o “cache”. Especificamente, isso significa que [limitar consultas](#limiting-querysets) usando o fatiamento de “array” ou um índice não irá popular o cache.

For example, repeatedly getting a certain index in a queryset object will query
the database each time:

```pycon
>>> queryset = Entry.objects.all()
>>> print(queryset[5])  # Queries the database
>>> print(queryset[5])  # Queries the database again
```

However, if the entire queryset has already been evaluated, the cache will be
checked instead:

```pycon
>>> queryset = Entry.objects.all()
>>> [entry for entry in queryset]  # Queries the database
>>> print(queryset[5])  # Uses cache
>>> print(queryset[5])  # Uses cache
```

Here are some examples of other actions that will result in the entire queryset
being evaluated and therefore populate the cache:

```pycon
>>> [entry for entry in queryset]
>>> bool(queryset)
>>> entry in queryset
>>> list(queryset)
```

> **Note**
>
> Simplesmente dar um “print” no “queryset” não popula o “cache”. Isso é porque a chamada do \_\_repr\_\_()\`\`somente retorna uma fatia de todo o “queryset”.

## Asynchronous queries

> **New in Django 4.1**

If you are writing asynchronous views or code, you cannot use the ORM for
queries in quite the way we have described above, as you cannot call *blocking*
synchronous code from asynchronous code - it will block up the event loop
(or, more likely, Django will notice and raise a `SynchronousOnlyOperation`
to stop that from happening).

Fortunately, you can do many queries using Django’s asynchronous query APIs.
Every method that might block - such as `get()` or `delete()` \- has an
asynchronous variant (`aget()` or `adelete()`), and when you iterate over
results, you can use asynchronous iteration (`async for`) instead.

### Query iteration

> **New in Django 4.1**

The default way of iterating over a query - with `for` \- will result in a
blocking database query behind the scenes as Django loads the results at
iteration time. To fix this, you can swap to `async for`:

```
async for entry in Authors.objects.filter(name__startswith="A"):
    ...
```

Be aware that you also can’t do other things that might iterate over the
queryset, such as wrapping `list()` around it to force its evaluation (you
can use `async for` in a comprehension, if you want it).

Because `QuerySet` methods like `filter()` and `exclude()` do not
actually run the query - they set up the queryset to run when it’s iterated
over - you can use those freely in asynchronous code. For a guide to which
methods can keep being used like this, and which have asynchronous versions,
read the next section.

### `QuerySet` and manager methods

> **New in Django 4.1**

Some methods on managers and querysets - like `get()` and `first()` \- force
execution of the queryset and are blocking. Some, like `filter()` and
`exclude()`, don’t force execution and so are safe to run from asynchronous
code. But how are you supposed to tell the difference?

While you could poke around and see if there is an `a`-prefixed version of
the method (for example, we have `aget()` but not `afilter()`), there is a
more logical way - look up what kind of method it is in the
[QuerySet reference](/pt-br/4.2/ref/models/querysets/).

In there, you’ll find the methods on QuerySets grouped into two sections:

- *Methods that return new querysets*: These are the non-blocking ones,
  and don’t have asynchronous versions. You’re free to use these in any
  situation, though read the notes on `defer()` and `only()` before you use
  them.
- *Methods that do not return querysets*: These are the blocking ones, and
  have asynchronous versions - the asynchronous name for each is noted in its
  documentation, though our standard pattern is to add an `a` prefix.

Using this distinction, you can work out when you need to use asynchronous
versions, and when you don’t. For example, here’s a valid asynchronous query:

```
user = await User.objects.filter(username=my_input).afirst()
```

`filter()` returns a queryset, and so it’s fine to keep chaining it inside an
asynchronous environment, whereas `first()` evaluates and returns a model
instance - thus, we change to `afirst()`, and use `await` at the front of
the whole expression in order to call it in an asynchronous-friendly way.

> **Note**
>
> If you forget to put the `await` part in, you may see errors like
> *“coroutine object has no attribute x”* or *“\<coroutine …\>”* strings in
> place of your model instances. If you ever see these, you are missing an
> `await` somewhere to turn that coroutine into a real value.

### Transações

> **New in Django 4.1**

Transactions are **not** currently supported with asynchronous queries and
updates. You will find that trying to use one raises
`SynchronousOnlyOperation`.

If you wish to use a transaction, we suggest you write your ORM code inside a
separate, synchronous function and then call that using `sync_to_async` \- see
[Suporte assíncrono](/pt-br/4.2/topics/async/) for more.

## Querying `JSONField`

Lookups implementation is different in [`JSONField`](/pt-br/4.2/ref/models/fields/#django.db.models.JSONField),
mainly due to the existence of key transformations. To demonstrate, we will use
the following example model:

```
from django.db import models

class Dog(models.Model):
    name = models.CharField(max_length=200)
    data = models.JSONField(null=True)

    def __str__(self):
        return self.name
```

### Storing and querying for `None`

As with other fields, storing `None` as the field’s value will store it as
SQL `NULL`. While not recommended, it is possible to store JSON scalar
`null` instead of SQL `NULL` by using [`Value(None, JSONField())`](/pt-br/4.2/ref/models/expressions/#django.db.models.Value).

Whichever of the values is stored, when retrieved from the database, the Python
representation of the JSON scalar `null` is the same as SQL `NULL`, i.e.
`None`. Therefore, it can be hard to distinguish between them.

This only applies to `None` as the top-level value of the field. If `None`
is inside a [`list`](https://docs.python.org/3/library/stdtypes.html#list) or [`dict`](https://docs.python.org/3/library/stdtypes.html#dict), it will always be interpreted
as JSON `null`.

When querying, `None` value will always be interpreted as JSON `null`. To
query for SQL `NULL`, use [`isnull`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-isnull):

```pycon
>>> Dog.objects.create(name="Max", data=None)  # SQL NULL.
<Dog: Max>
>>> Dog.objects.create(name="Archie", data=Value(None, JSONField()))  # JSON null.
<Dog: Archie>
>>> Dog.objects.filter(data=None)
<QuerySet [<Dog: Archie>]>
>>> Dog.objects.filter(data=Value(None, JSONField()))
<QuerySet [<Dog: Archie>]>
>>> Dog.objects.filter(data__isnull=True)
<QuerySet [<Dog: Max>]>
>>> Dog.objects.filter(data__isnull=False)
<QuerySet [<Dog: Archie>]>
```

Unless you are sure you wish to work with SQL `NULL` values, consider setting
`null=False` and providing a suitable default for empty values, such as
`default=dict`.

> **Note**
>
> Storing JSON scalar `null` does not violate [`null=False`](/pt-br/4.2/ref/models/fields/#django.db.models.Field.null).

> **Changed in Django 4.2**
>
> Support for expressing JSON `null` using `Value(None, JSONField())` was
> added.

> **Deprecated since Django 4.2**
>
> Descontinuado desde a versão 4.2: Passing `Value("null")` to express JSON `null` is deprecated.

### Key, index, and path transforms

To query based on a given dictionary key, use that key as the lookup name:

```pycon
>>> Dog.objects.create(
...     name="Rufus",
...     data={
...         "breed": "labrador",
...         "owner": {
...             "name": "Bob",
...             "other_pets": [
...                 {
...                     "name": "Fishy",
...                 }
...             ],
...         },
...     },
... )
<Dog: Rufus>
>>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": None})
<Dog: Meg>
>>> Dog.objects.filter(data__breed="collie")
<QuerySet [<Dog: Meg>]>
```

Multiple keys can be chained together to form a path lookup:

```pycon
>>> Dog.objects.filter(data__owner__name="Bob")
<QuerySet [<Dog: Rufus>]>
```

If the key is an integer, it will be interpreted as an index transform in an
array:

```pycon
>>> Dog.objects.filter(data__owner__other_pets__0__name="Fishy")
<QuerySet [<Dog: Rufus>]>
```

If the key you wish to query by clashes with the name of another lookup, use
the [`contains`](#std-fieldlookup-jsonfield.contains) lookup instead.

To query for missing keys, use the `isnull` lookup:

```pycon
>>> Dog.objects.create(name="Shep", data={"breed": "collie"})
<Dog: Shep>
>>> Dog.objects.filter(data__owner__isnull=True)
<QuerySet [<Dog: Shep>]>
```

> **Note**
>
> The lookup examples given above implicitly use the [`exact`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-exact) lookup.
> Key, index, and path transforms can also be chained with:
> [`icontains`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-icontains), [`endswith`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-endswith), [`iendswith`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-iendswith),
> [`iexact`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-iexact), [`regex`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-regex), [`iregex`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-iregex), [`startswith`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-startswith),
> [`istartswith`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-istartswith), [`lt`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-lt), [`lte`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-lte), [`gt`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-gt), and
> [`gte`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-gte), as well as with [Containment and key lookups](#containment-and-key-lookups).

#### `KT()` expressions

> **New in Django 4.2**

#### `class KT(lookup)`

Represents the text value of a key, index, or path transform of
[`JSONField`](/pt-br/4.2/ref/models/fields/#django.db.models.JSONField). You can use the double underscore
notation in `lookup` to chain dictionary key and index transforms.

Por exemplo:

```pycon
>>> from django.db.models.fields.json import KT
>>> Dog.objects.create(
...     name="Shep",
...     data={
...         "owner": {"name": "Bob"},
...         "breed": ["collie", "lhasa apso"],
...     },
... )
<Dog: Shep>
>>> Dogs.objects.annotate(
...     first_breed=KT("data__breed__1"), owner_name=KT("data__owner__name")
... ).filter(first_breed__startswith="lhasa", owner_name="Bob")
<QuerySet [<Dog: Shep>]>
```

> **Note**
>
> Due to the way in which key-path queries work,
> [`exclude()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.exclude) and
> [`filter()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.filter) are not guaranteed to
> produce exhaustive sets. If you want to include objects that do not have
> the path, add the `isnull` lookup.

> **Warning**
>
> Since any string could be a key in a JSON object, any lookup other than
> those listed below will be interpreted as a key lookup. No errors are
> raised. Be extra careful for typing mistakes, and always check your queries
> work as you intend.

> **MariaDB and Oracle users**
>
> Using [`order_by()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.order_by) on key, index, or
> path transforms will sort the objects using the string representation of
> the values. This is because MariaDB and Oracle Database do not provide a
> function that converts JSON values into their equivalent SQL values.

> **Oracle users**
>
> On Oracle Database, using `None` as the lookup value in an
> [`exclude()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.exclude) query will return objects
> that do not have `null` as the value at the given path, including objects
> that do not have the path. On other database backends, the query will
> return objects that have the path and the value is not `null`.

> **PostgreSQL users**
>
> On PostgreSQL, if only one key or index is used, the SQL operator `->` is
> used. If multiple operators are used then the `#>` operator is used.

> **SQLite users**
>
> On SQLite, `"true"`, `"false"`, and `"null"` string values will
> always be interpreted as `True`, `False`, and JSON `null`
> respectively.

### Containment and key lookups

#### `contains`

The [`contains`](/pt-br/4.2/ref/models/querysets/#std-fieldlookup-contains) lookup is overridden on `JSONField`. The returned
objects are those where the given `dict` of key-value pairs are all
contained in the top-level of the field. For example:

```pycon
>>> Dog.objects.create(name="Rufus", data={"breed": "labrador", "owner": "Bob"})
<Dog: Rufus>
>>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
<Dog: Meg>
>>> Dog.objects.create(name="Fred", data={})
<Dog: Fred>
>>> Dog.objects.filter(data__contains={"owner": "Bob"})
<QuerySet [<Dog: Rufus>, <Dog: Meg>]>
>>> Dog.objects.filter(data__contains={"breed": "collie"})
<QuerySet [<Dog: Meg>]>
```

> **Oracle and SQLite**
>
> `contains` is not supported on Oracle and SQLite.

#### `contained_by`

This is the inverse of the [`contains`](#std-fieldlookup-jsonfield.contains) lookup - the
objects returned will be those where the key-value pairs on the object are a
subset of those in the value passed. For example:

```pycon
>>> Dog.objects.create(name="Rufus", data={"breed": "labrador", "owner": "Bob"})
<Dog: Rufus>
>>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
<Dog: Meg>
>>> Dog.objects.create(name="Fred", data={})
<Dog: Fred>
>>> Dog.objects.filter(data__contained_by={"breed": "collie", "owner": "Bob"})
<QuerySet [<Dog: Meg>, <Dog: Fred>]>
>>> Dog.objects.filter(data__contained_by={"breed": "collie"})
<QuerySet [<Dog: Fred>]>
```

> **Oracle and SQLite**
>
> `contained_by` is not supported on Oracle and SQLite.

#### `has_key`

Returns objects where the given key is in the top-level of the data. For
example:

```pycon
>>> Dog.objects.create(name="Rufus", data={"breed": "labrador"})
<Dog: Rufus>
>>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
<Dog: Meg>
>>> Dog.objects.filter(data__has_key="owner")
<QuerySet [<Dog: Meg>]>
```

#### `has_keys`

Returns objects where all of the given keys are in the top-level of the data.
For example:

```pycon
>>> Dog.objects.create(name="Rufus", data={"breed": "labrador"})
<Dog: Rufus>
>>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
<Dog: Meg>
>>> Dog.objects.filter(data__has_keys=["breed", "owner"])
<QuerySet [<Dog: Meg>]>
```

#### `has_any_keys`

Returns objects where any of the given keys are in the top-level of the data.
For example:

```pycon
>>> Dog.objects.create(name="Rufus", data={"breed": "labrador"})
<Dog: Rufus>
>>> Dog.objects.create(name="Meg", data={"owner": "Bob"})
<Dog: Meg>
>>> Dog.objects.filter(data__has_any_keys=["owner", "breed"])
<QuerySet [<Dog: Rufus>, <Dog: Meg>]>
```

## Consultas complexas com objetos `Q`

Consultas com argumentos nomeados – no [`filter()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.filter), etc. – compõem uma “E”. Se você precisa executar consultas mais complexas (por exemplo, consultas com comandos `OR`), você pode usar [`Q objects`](/pt-br/4.2/ref/models/querysets/#django.db.models.Q).

Um [`objeto Q`](/pt-br/4.2/ref/models/querysets/#django.db.models.Q) (`django.db.models.Q`) é um objeto usado para encapsular uma coleção de argumentos nomeados. Estes argumentos são especificados como um “campo de filtro” acima.

Por exemplo, este objeto `Q` encapsula uma única consulta `LIKE`:

```
from django.db.models import Q

Q(question__startswith="What")
```

`Q` objects can be combined using the `&`, `|`, and `^` operators. When
an operator is used on two `Q` objects, it yields a new `Q` object.

Por exemplo, este comando produz um único objeto `Q` que representa o `OR` de duas consultas `"question__startswith"`:

```
Q(question__startswith="Who") | Q(question__startswith="What")
```

This is equivalent to the following SQL `WHERE` clause:

```sql
WHERE question LIKE 'Who%' OR question LIKE 'What%'
```

You can compose statements of arbitrary complexity by combining `Q` objects
with the `&`, `|`, and `^` operators and use parenthetical grouping.
Also, `Q` objects can be negated using the `~` operator, allowing for
combined lookups that combine both a normal query and a negated (`NOT`)
query:

```
Q(question__startswith="Who") | ~Q(pub_date__year=2005)
```

Para cada função de filtro que recebe argumentos nominados (ex.: [`filter()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.filter), [`exclude()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.exclude), [`get()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.get)) pode também se passado um ou mais objetos Q\`\`como argumentos posicionais (not-named). Se você prover múltiplos objetos Q\`\`para uma função filtro, os argumentos serão interpolados com lógicas “E”. Por exemplo:

```
Poll.objects.get(
    Q(question__startswith="Who"),
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
)
```

… roughly translates into the SQL:

```sql
SELECT * from polls WHERE question LIKE 'Who%'
    AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')
```

Funções de filtro podem misturar o uso de objetos `Q` e argumentos nomeados. Todos os argumentos fornecidos para uma função filtro (sejam eles argumentos nomeados ou objetos `Q`)  são interpolados com “E”. Porém, se um objeto `Q` é fornecido, é necessário que este preceda qualquer argumento nomeado. Por exemplo:

```
Poll.objects.get(
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
    question__startswith="Who",
)
```

… seria uma consulta válida, equivalente ao exemplo anterior; mas:

```
# INVALID QUERY
Poll.objects.get(
    question__startswith="Who",
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
)
```

… não seria válido.

> **See also**
>
> The [OR lookups examples](https://github.com/django/django/blob/stable/4.2.x/tests/or_lookups/tests.py) in Django’s
> unit tests show some possible uses of `Q`.

> **Changed in Django 4.1**
>
> Support for the `^` (`XOR`) operator was added.

## Comparando objetos

To compare two model instances, use the standard Python comparison operator,
the double equals sign: `==`. Behind the scenes, that compares the primary
key values of two models.

Using the `Entry` example above, the following two statements are equivalent:

```pycon
>>> some_entry == other_entry
>>> some_entry.id == other_entry.id
```

If a model’s primary key isn’t called `id`, no problem. Comparisons will
always use the primary key, whatever it’s called. For example, if a model’s
primary key field is called `name`, these two statements are equivalent:

```pycon
>>> some_obj == other_obj
>>> some_obj.name == other_obj.name
```

## Deletando objetos

The delete method, conveniently, is named
[`delete()`](/pt-br/4.2/ref/models/instances/#django.db.models.Model.delete). This method immediately deletes the
object and returns the number of objects deleted and a dictionary with
the number of deletions per object type. Example:

```pycon
>>> e.delete()
(1, {'blog.Entry': 1})
```

Você também pode deletar objetos em massa. Cada [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) tem um método [`delete()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.delete), o qual deleta todos os membros daquele [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet).

For example, this deletes all `Entry` objects with a `pub_date` year of
2005:

```pycon
>>> Entry.objects.filter(pub_date__year=2005).delete()
(5, {'webapp.Entry': 5})
```

Keep in mind that this will, whenever possible, be executed purely in SQL, and
so the `delete()` methods of individual object instances will not necessarily
be called during the process. If you’ve provided a custom `delete()` method
on a model class and want to ensure that it is called, you will need to
“manually” delete instances of that model (e.g., by iterating over a
[`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) and calling `delete()` on each
object individually) rather than using the bulk
[`delete()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.delete) method of a
[`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet).

When Django deletes an object, by default it emulates the behavior of the SQL
constraint `ON DELETE CASCADE` – in other words, any objects which had
foreign keys pointing at the object to be deleted will be deleted along with
it. For example:

```
b = Blog.objects.get(pk=1)
# This will delete the Blog and all of its Entry objects.
b.delete()
```

This cascade behavior is customizable via the
[`on_delete`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey.on_delete) argument to the
[`ForeignKey`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey).

Note that [`delete()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.delete) is the only
[`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) method that is not exposed on a
[`Manager`](/pt-br/4.2/topics/db/managers/#django.db.models.Manager) itself. This is a safety mechanism to
prevent you from accidentally requesting `Entry.objects.delete()`, and
deleting *all* the entries. If you *do* want to delete all the objects, then
you have to explicitly request a complete query set:

```
Entry.objects.all().delete()
```

## Copiando as instâncias de modelo

Although there is no built-in method for copying model instances, it is
possible to easily create new instance with all fields’ values copied. In the
simplest case, you can set `pk` to `None` and
[`_state.adding`](/pt-br/4.2/ref/models/instances/#django.db.models.Model._state) to `True`. Using our
blog example:

```
blog = Blog(name="My blog", tagline="Blogging is easy")
blog.save()  # blog.pk == 1

blog.pk = None
blog._state.adding = True
blog.save()  # blog.pk == 2
```

Things get more complicated if you use inheritance. Consider a subclass of
`Blog`:

```
class ThemeBlog(Blog):
    theme = models.CharField(max_length=200)

django_blog = ThemeBlog(name="Django", tagline="Django is easy", theme="python")
django_blog.save()  # django_blog.pk == 3
```

Due to how inheritance works, you have to set both `pk` and `id` to
`None`, and `_state.adding` to `True`:

```
django_blog.pk = None
django_blog.id = None
django_blog._state.adding = True
django_blog.save()  # django_blog.pk == 4
```

This process doesn’t copy relations that aren’t part of the model’s database
table. For example, `Entry` has a `ManyToManyField` to `Author`. After
duplicating an entry, you must set the many-to-many relations for the new
entry:

```
entry = Entry.objects.all()[0]  # some previous entry
old_authors = entry.authors.all()
entry.pk = None
entry._state.adding = True
entry.save()
entry.authors.set(old_authors)
```

For a `OneToOneField`, you must duplicate the related object and assign it
to the new object’s field to avoid violating the one-to-one unique constraint.
For example, assuming `entry` is already duplicated as above:

```
detail = EntryDetail.objects.all()[0]
detail.pk = None
detail._state.adding = True
detail.entry = entry
detail.save()
```

## Alterando múltiplos objetos de uma só vez.

Algumas vezes você querer definir um campo para um particular valor para todos os objetos em uma . Você pode fazer isto com o  método. Por exemplo:

```
# Update all the headlines with pub_date in 2007.
Entry.objects.filter(pub_date__year=2007).update(headline="Everything is the same")
```

You can only set non-relation fields and [`ForeignKey`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey)
fields using this method. To update a non-relation field, provide the new value
as a constant. To update [`ForeignKey`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey) fields, set the
new value to be the new model instance you want to point to. For example:

```pycon
>>> b = Blog.objects.get(pk=1)

# Change every Entry so that it belongs to this Blog.
>>> Entry.objects.update(blog=b)
```

The `update()` method is applied instantly and returns the number of rows
matched by the query (which may not be equal to the number of rows updated if
some rows already have the new value). The only restriction on the
[`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) being updated is that it can only
access one database table: the model’s main table. You can filter based on
related fields, but you can only update columns in the model’s main
table. Example:

```pycon
>>> b = Blog.objects.get(pk=1)

# Update all the headlines belonging to this Blog.
>>> Entry.objects.filter(blog=b).update(headline="Everything is the same")
```

Be aware that the `update()` method is converted directly to an SQL
statement. It is a bulk operation for direct updates. It doesn’t run any
[`save()`](/pt-br/4.2/ref/models/instances/#django.db.models.Model.save) methods on your models, or emit the
`pre_save` or `post_save` signals (which are a consequence of calling
[`save()`](/pt-br/4.2/ref/models/instances/#django.db.models.Model.save)), or honor the
[`auto_now`](/pt-br/4.2/ref/models/fields/#django.db.models.DateField.auto_now) field option.
If you want to save every item in a [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet)
and make sure that the [`save()`](/pt-br/4.2/ref/models/instances/#django.db.models.Model.save) method is called on
each instance, you don’t need any special function to handle that. Loop over
them and call [`save()`](/pt-br/4.2/ref/models/instances/#django.db.models.Model.save):

```
for item in my_queryset:
    item.save()
```

Calls to update can also use [`F expressions`](/pt-br/4.2/ref/models/expressions/#django.db.models.F) to
update one field based on the value of another field in the model. This is
especially useful for incrementing counters based upon their current value. For
example, to increment the pingback count for every entry in the blog:

```pycon
>>> Entry.objects.update(number_of_pingbacks=F("number_of_pingbacks") + 1)
```

However, unlike `F()` objects in filter and exclude clauses, you can’t
introduce joins when you use `F()` objects in an update – you can only
reference fields local to the model being updated. If you attempt to introduce
a join with an `F()` object, a `FieldError` will be raised:

```pycon
# This will raise a FieldError
>>> Entry.objects.update(headline=F("blog__name"))
```

## Objetos relacionados

When you define a relationship in a model (i.e., a
[`ForeignKey`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey),
[`OneToOneField`](/pt-br/4.2/ref/models/fields/#django.db.models.OneToOneField), or
[`ManyToManyField`](/pt-br/4.2/ref/models/fields/#django.db.models.ManyToManyField)), instances of that model will have
a convenient API to access the related object(s).

Using the models at the top of this page, for example, an `Entry` object `e`
can get its associated `Blog` object by accessing the `blog` attribute:
`e.blog`.

(Behind the scenes, this functionality is implemented by Python
[descriptors](https://docs.python.org/3/howto/descriptor.html). This shouldn’t really matter to
you, but we point it out here for the curious.)

Django also creates API accessors for the “other” side of the relationship –
the link from the related model to the model that defines the relationship.
For example, a `Blog` object `b` has access to a list of all related
`Entry` objects via the `entry_set` attribute: `b.entry_set.all()`.

All examples in this section use the sample `Blog`, `Author` and `Entry`
models defined at the top of this page.

### Relações One-to-many

#### Adiante

If a model has a [`ForeignKey`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey), instances of that model
will have access to the related (foreign) object via an attribute of the model.

Example:

```pycon
>>> e = Entry.objects.get(id=2)
>>> e.blog  # Returns the related Blog object.
```

You can get and set via a foreign-key attribute. As you may expect, changes to
the foreign key aren’t saved to the database until you call
[`save()`](/pt-br/4.2/ref/models/instances/#django.db.models.Model.save). Example:

```pycon
>>> e = Entry.objects.get(id=2)
>>> e.blog = some_blog
>>> e.save()
```

If a [`ForeignKey`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey) field has `null=True` set (i.e.,
it allows `NULL` values), you can assign `None` to remove the relation.
Example:

```pycon
>>> e = Entry.objects.get(id=2)
>>> e.blog = None
>>> e.save()  # "UPDATE blog_entry SET blog_id = NULL ...;"
```

Forward access to one-to-many relationships is cached the first time the
related object is accessed. Subsequent accesses to the foreign key on the same
object instance are cached. Example:

```pycon
>>> e = Entry.objects.get(id=2)
>>> print(e.blog)  # Hits the database to retrieve the associated Blog.
>>> print(e.blog)  # Doesn't hit the database; uses cached version.
```

Note that the [`select_related()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.select_related)
[`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) method recursively prepopulates the
cache of all one-to-many relationships ahead of time. Example:

```pycon
>>> e = Entry.objects.select_related().get(id=2)
>>> print(e.blog)  # Doesn't hit the database; uses cached version.
>>> print(e.blog)  # Doesn't hit the database; uses cached version.
```

#### Following relationships “backward”

If a model has a [`ForeignKey`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey), instances of the
foreign-key model will have access to a [`Manager`](/pt-br/4.2/topics/db/managers/#django.db.models.Manager) that
returns all instances of the first model. By default, this
[`Manager`](/pt-br/4.2/topics/db/managers/#django.db.models.Manager) is named `FOO_set`, where `FOO` is the
source model name, lowercased. This [`Manager`](/pt-br/4.2/topics/db/managers/#django.db.models.Manager) returns
`QuerySets`, which can be filtered and manipulated as described in the
“Retrieving objects” section above.

Example:

```pycon
>>> b = Blog.objects.get(id=1)
>>> b.entry_set.all()  # Returns all Entry objects related to Blog.

# b.entry_set is a Manager that returns QuerySets.
>>> b.entry_set.filter(headline__contains="Lennon")
>>> b.entry_set.count()
```

You can override the `FOO_set` name by setting the
[`related_name`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey.related_name) parameter in the
[`ForeignKey`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey) definition. For example, if the `Entry`
model was altered to `blog = ForeignKey(Blog, on_delete=models.CASCADE,
related_name='entries')`, the above example code would look like this:

```pycon
>>> b = Blog.objects.get(id=1)
>>> b.entries.all()  # Returns all Entry objects related to Blog.

# b.entries is a Manager that returns QuerySets.
>>> b.entries.filter(headline__contains="Lennon")
>>> b.entries.count()
```

#### Using a custom reverse manager

By default the [`RelatedManager`](/pt-br/4.2/ref/models/relations/#django.db.models.fields.related.RelatedManager) used
for reverse relations is a subclass of the [default manager](/pt-br/4.2/topics/db/managers/#manager-names)
for that model. If you would like to specify a different manager for a given
query you can use the following syntax:

```
from django.db import models

class Entry(models.Model):
    # ...
    objects = models.Manager()  # Default Manager
    entries = EntryManager()  # Custom Manager

b = Blog.objects.get(id=1)
b.entry_set(manager="entries").all()
```

If `EntryManager` performed default filtering in its `get_queryset()`
method, that filtering would apply to the `all()` call.

Specifying a custom reverse manager also enables you to call its custom
methods:

```
b.entry_set(manager="entries").is_published()
```

> **Interaction with prefetching**
>
> When calling [`prefetch_related()`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet.prefetch_related) with
> a reverse relation, the default manager will be used. If you want to
> prefetch related objects using a custom reverse manager, use
> [`Prefetch()`](/pt-br/4.2/ref/models/querysets/#django.db.models.Prefetch). For example:
>
> ```
> from django.db.models import Prefetch
>
> prefetch_manager = Prefetch("entry_set", queryset=Entry.entries.all())
> Blog.objects.prefetch_related(prefetch_manager)
> ```

#### Additional methods to handle related objects

In addition to the [`QuerySet`](/pt-br/4.2/ref/models/querysets/#django.db.models.query.QuerySet) methods defined in
“Retrieving objects” above, the [`ForeignKey`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey)
[`Manager`](/pt-br/4.2/topics/db/managers/#django.db.models.Manager) has additional methods used to handle the
set of related objects. A synopsis of each is below, and complete details can
be found in the [related objects reference](/pt-br/4.2/ref/models/relations/).

**`add(obj1, obj2, ...)`**

  Adds the specified model objects to the related object set.

**`create(**kwargs)`**

  Creates a new object, saves it and puts it in the related object set.
  Returns the newly created object.

**`remove(obj1, obj2, ...)`**

  Removes the specified model objects from the related object set.

**`clear()`**

  Removes all objects from the related object set.

**`set(objs)`**

  Replace the set of related objects.

To assign the members of a related set, use the `set()` method with an
iterable of object instances. For example, if `e1` and `e2` are `Entry`
instances:

```
b = Blog.objects.get(id=1)
b.entry_set.set([e1, e2])
```

If the `clear()` method is available, any preexisting objects will be
removed from the `entry_set` before all objects in the iterable (in this
case, a list) are added to the set. If the `clear()` method is *not*
available, all objects in the iterable will be added without removing any
existing elements.

Each “reverse” operation described in this section has an immediate effect on
the database. Every addition, creation and deletion is immediately and
automatically saved to the database.

### Many-to-many relationships

Both ends of a many-to-many relationship get automatic API access to the other
end. The API works similar to a “backward” one-to-many relationship, above.

One difference is in the attribute naming: The model that defines the
[`ManyToManyField`](/pt-br/4.2/ref/models/fields/#django.db.models.ManyToManyField) uses the attribute name of that
field itself, whereas the “reverse” model uses the lowercased model name of the
original model, plus `'_set'` (just like reverse one-to-many relationships).

An example makes this easier to understand:

```
e = Entry.objects.get(id=3)
e.authors.all()  # Returns all Author objects for this Entry.
e.authors.count()
e.authors.filter(name__contains="John")

a = Author.objects.get(id=5)
a.entry_set.all()  # Returns all Entry objects for this Author.
```

Like [`ForeignKey`](/pt-br/4.2/ref/models/fields/#django.db.models.ForeignKey),
[`ManyToManyField`](/pt-br/4.2/ref/models/fields/#django.db.models.ManyToManyField) can specify
[`related_name`](/pt-br/4.2/ref/models/fields/#django.db.models.ManyToManyField.related_name). In the above example,
if the [`ManyToManyField`](/pt-br/4.2/ref/models/fields/#django.db.models.ManyToManyField) in `Entry` had specified
`related_name='entries'`, then each `Author` instance would have an
`entries` attribute instead of `entry_set`.

Another difference from one-to-many relationships is that in addition to model
instances,  the `add()`, `set()`, and `remove()` methods on many-to-many
relationships accept primary key values. For example, if `e1` and `e2` are
`Entry` instances, then these `set()` calls work identically:

```
a = Author.objects.get(id=5)
a.entry_set.set([e1, e2])
a.entry_set.set([e1.pk, e2.pk])
```

### One-to-one relationships

One-to-one relationships are very similar to many-to-one relationships. If you
define a [`OneToOneField`](/pt-br/4.2/ref/models/fields/#django.db.models.OneToOneField) on your model, instances of
that model will have access to the related object via an attribute of the
model.

Por exemplo:

```
class EntryDetail(models.Model):
    entry = models.OneToOneField(Entry, on_delete=models.CASCADE)
    details = models.TextField()

ed = EntryDetail.objects.get(id=2)
ed.entry  # Returns the related Entry object.
```

The difference comes in “reverse” queries. The related model in a one-to-one
relationship also has access to a [`Manager`](/pt-br/4.2/topics/db/managers/#django.db.models.Manager) object, but
that [`Manager`](/pt-br/4.2/topics/db/managers/#django.db.models.Manager) represents a single object, rather than
a collection of objects:

```
e = Entry.objects.get(id=2)
e.entrydetail  # returns the related EntryDetail object
```

If no object has been assigned to this relationship, Django will raise
a `DoesNotExist` exception.

Instances can be assigned to the reverse relationship in the same way as
you would assign the forward relationship:

```
e.entrydetail = ed
```

### How are the backward relationships possible?

Other object-relational mappers require you to define relationships on both
sides. The Django developers believe this is a violation of the DRY (Don’t
Repeat Yourself) principle, so Django only requires you to define the
relationship on one end.

But how is this possible, given that a model class doesn’t know which other
model classes are related to it until those other model classes are loaded?

The answer lies in the [`app registry`](/pt-br/4.2/ref/applications/#django.apps.apps). When Django
starts, it imports each application listed in [`INSTALLED_APPS`](/pt-br/4.2/ref/settings/#std-setting-INSTALLED_APPS), and
then the `models` module inside each application. Whenever a new model class
is created, Django adds backward-relationships to any related models. If the
related models haven’t been imported yet, Django keeps tracks of the
relationships and adds them when the related models eventually are imported.

For this reason, it’s particularly important that all the models you’re using
be defined in applications listed in [`INSTALLED_APPS`](/pt-br/4.2/ref/settings/#std-setting-INSTALLED_APPS). Otherwise,
backwards relations may not work properly.

### Queries over related objects

Queries involving related objects follow the same rules as queries involving
normal value fields. When specifying the value for a query to match, you may
use either an object instance itself, or the primary key value for the object.

For example, if you have a Blog object `b` with `id=5`, the following
three queries would be identical:

```
Entry.objects.filter(blog=b)  # Query using object instance
Entry.objects.filter(blog=b.id)  # Query using id from instance
Entry.objects.filter(blog=5)  # Query using id directly
```

## Falling back to raw SQL

If you find yourself needing to write an SQL query that is too complex for
Django’s database-mapper to handle, you can fall back on writing SQL by hand.
Django has a couple of options for writing raw SQL queries; see
[Performing raw SQL queries](/pt-br/4.2/topics/db/sql/).

Finally, it’s important to note that the Django database layer is merely an
interface to your database. You can access your database via other tools,
programming languages or database frameworks; there’s nothing Django-specific
about your database.
