Contenido del Curso
Django ORM Ninja: Técnicas Avanzadas para Desarrolladores
Django ORM Ninja: Técnicas Avanzadas para Desarrolladores
ForeignKey Arguments
To define a Many-to-One relation, models.ForeignKey
is used. The first argument corresponds to the model to relate to, and the second, 'on_delete', specifies the behavior when the related object is deleted. The options include:
- CASCADE: Deleting a genre deletes all associated books.
- PROTECT: Prevents deletion if there are related books.
- SET_NULL: Sets the genre to Null if null=True in model definition.
- SET_DEFAULT: Sets a default value if the genre is deleted if there available some default value.
- DO_NOTHING: No action, but may lead to IntegrityError.
The related_name
argument in ForeignKey is useful for reverse relation from the Genre
model back to Book
model. If you don't specify a related_name
, Django automatically creates one using the name of your model with the suffix _set (Genre.book_set.all()).
In our case works:
This structure provides a clear understanding of the Many-to-One relationship in Django, showcasing how to define and utilize it effectively.
¡Gracias por tus comentarios!