开发者

ManyToManyField Relationships Between Multiple Models

开发者 https://www.devze.com 2023-04-08 01:02 出处:网络
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 lin

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 cre开发者_StackOverflowated 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).

0

精彩评论

暂无评论...
验证码 换一张
取 消