Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django ManyToMany model: unable to access one relation from the other

My models.py:

class Author(models.Model):
    name = models.CharField(max_length=100)
    books = models.ManyToManyField(
        "Book", related_name="books", blank=True
    )

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ManyToManyField(Author)

In Django admin I first created an instance of Author, without assigning him any Book:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Then I created a new Book and assigned Leo Tolstoy as theAuthor:

enter image description here

In Django shell, I am able to access the Book‘s Author:

>>> Book.objects.filter(title="War and Peace").first().author.first()
<Author: Leo Tolstoy>

But I’m unable to access the Author‘s Books:

>>> Author.objects.filter(name="Leo Tolstoy").first().books.all()
<QuerySet []>

The book isn’t assigned in the Admin view either:

enter image description here

I would like to access the Author‘s Books as well as for the Books
to show in the Author‘s Admin view.

>Solution :

You only need one ManyToManyField. You should also pass "books" as the related_name on Book.authors as this is the name Django will use for the many-to-many manager attribute it automatically adds to Author instances.

See the example in the Django docs for more info.

When a ManyToManyField is created on both sides of a relation, Django is creating two associative tables between the book and author tables under the hood. Changes to one table don’t affect the other.

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(
        Author, related_name="books", blank=True
    )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading