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)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With