Multilateral relationships between multiple models

I have the following models that represent books and authors. There can be several authors in one book, and an author could write several books. Therefore, I use the Django type ManyToManyFieldto link the two models together.

I can add Book, possibly using Django Admin, and create Authorin this process. But when I browse Author, I just created it, not related to Book. I have to explicitly establish feedback between the instance Authorand the instance Book.

Is it the way it is, or can I do something else?

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)
+5
source share
1 answer

ManyToManyField, ManyToManyField . .: https://docs.djangoproject.com/en/dev/topics/db/queries/#many-to-many-relationships

:

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)

Author a, a.book_set.all() , ( ).

+7

All Articles