Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Many-to-Many | Relations
Django ORM Ninja: Técnicas Avanzadas para Desarrolladores
course content

Contenido del Curso

Django ORM Ninja: Técnicas Avanzadas para Desarrolladores

Django ORM Ninja: Técnicas Avanzadas para Desarrolladores

1. Introduction to Django ORM
2. Models, datatypes, and fields
3. Queries
4. Relations
5. Complex Queries
6. Advanced

bookMany-to-Many

A Many-to-Many relationship occurs when each record in a model can be associated with many records in another model, and vice versa. This is facilitated by Django's ManyToManyField.

Let's explore the ManyToManyField with an example. In our project, we use two models: Author and Book. An author can write multiple books, and a book might be co-authored by multiple authors. This is a classic many-to-many relationship.

Let’s implement it in our code. In the models.py add to the Book model a new field.

Accessing Related Records

From Author to Books:

From Book to Authors:

Adding and Removing Relationships

Adding an author to a book:

Removing an author from a book:

Filtering with ManyToManyField

You can also filter queries based on Many-to-Many relationships. For example, to find all books co-authored by a specific author:

1. How can you access all books written by an author named 'Richard Bachman'?
2. What Django query is used to add an author to a book?
3. How can you find all books co-authored by 'Richard Bachman'?
How can you access all books written by an author named 'Richard Bachman'?

How can you access all books written by an author named 'Richard Bachman'?

Selecciona unas respuestas correctas

What Django query is used to add an author to a book?

What Django query is used to add an author to a book?

Selecciona la respuesta correcta

How can you find all books co-authored by 'Richard Bachman'?

How can you find all books co-authored by 'Richard Bachman'?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 4
some-alt