Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ManyToManyField Relationships Between Multiple Models

I have the following models that represent books and authors. A single book can have multiple authors and an author could have written multiple books. So I am using Django's ManyToManyField type to link the two models to each other.

I can add a Book, using the Django Admin perhaps, and create an Author in the process. But when I view the Author I just created it's not linked to the Book. I have to explicitly set the reverse relationship between the Author instance and the Book instance.

Is that just the way it is or could I be doing something different?

Models.py

class Book(models.Model):    
    book_title = models.CharField(max_length=255, blank=False)
    authors = models.ManyToManyField('Author', blank=True)

class Author(models.Model):
    author_first_name = models.CharField(max_length=255, blank=False)
    author_last_name = models.CharField(max_length=255, blank=False)
    books = models.ManyToManyField(Book, blank=True)
like image 871
Raj Avatar asked Sep 26 '11 21:09

Raj


1 Answers

You don't need two ManyToManyField definitions because the model class without the ManyToManyField is related to the other through the reverse relationship. See: https://docs.djangoproject.com/en/dev/topics/db/queries/#many-to-many-relationships

If you defined the two model classes as:

class Book(models.Model):    
    book_title = models.CharField(max_length=255, blank=False)
    authors = models.ManyToManyField('Author', blank=True)

class Author(models.Model):
    author_first_name = models.CharField(max_length=255, blank=False)
    author_last_name = models.CharField(max_length=255, blank=False)

then for any Author instance a, a.book_set.all() consists of the books that the author wrote (or co-wrote).

like image 170
Daniel Trebbien Avatar answered Nov 14 '22 22:11

Daniel Trebbien