ForeignKey e on_delete
Modele relações um-para-muitos e o comportamento de exclusão
ForeignKey e on_delete é uma aula grátis de Django Academy no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Django Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Django Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Linking Two Tables
Real data connects: a book has an author, an order has a customer. A ForeignKey is how one model points to another.
One-to-Many at a Glance
A ForeignKey models a one-to-many link. One author can have many books, but each book belongs to exactly one author.
Declaring a ForeignKey
Add a field of type ForeignKey and point it at the related model. Django stores the link as an id column behind the scenes.
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)The _id Column
In the database, an author ForeignKey becomes an author_id column holding the other row's primary key. That number is the actual link.
on_delete Is Required
Every ForeignKey needs on_delete. It tells Django what to do with this row when the row it points to is deleted.
CASCADE Deletes Children
CASCADE deletes this row too when its parent goes. Remove an author and all their books vanish with them.
author = models.ForeignKey(Author, on_delete=models.CASCADE)PROTECT Blocks Deletion
Use PROTECT to refuse the delete while related rows exist. Django raises an error instead of removing the parent.
author = models.ForeignKey(Author, on_delete=models.PROTECT)SET_NULL Keeps the Child
SET_NULL keeps the row but clears the link, setting the column to NULL. It needs null=True on the field to work.
author = models.ForeignKey(Author, null=True, on_delete=models.SET_NULL)SET_DEFAULT and DO_NOTHING
SET_DEFAULT swaps in the field's default, while DO_NOTHING leaves the database to decide. Reach for these only in special cases.
Accessing the Related Object
From a book instance you read the linked author straight through the field. Django fetches that row for you on demand.
book = Book.objects.first()
print(book.author.name)Filtering Across the Link
Span the relationship in queries with the double underscore. Reach into the related model's fields directly from filter.
Book.objects.filter(author__name="Ada")Quick Check
You delete an author but want their books to stay, just unlinked. Which on_delete value fits?
Recap
Nice work! A ForeignKey models one-to-many links, and on_delete decides each row's fate when its parent is removed. 🔗
Aprenda Python com um tutor de IA — grátis
Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.
- Cursos
- 30
- Aulas
- 120
Perguntas Frequentes
A aula “ForeignKey e on_delete” é grátis?
Sim — o texto completo de “ForeignKey e on_delete” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Django Academy, atualize para CoddyKit PRO. O curso de Django Academy inclui 4 aulas no total.
O que vou aprender em “ForeignKey e on_delete”?
Modele relações um-para-muitos e o comportamento de exclusão Você pratica Django Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Django Academy?
Nenhuma experiência prévia é necessária. Django Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.
Quanto tempo leva a aula “ForeignKey e on_delete”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Django Academy?
Sim. Cada aula de Django Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- ForeignKey e on_delete
- ManyToManyField e modelos intermediários
- OneToOneField para perfis
- related_name e consultas reversas