ManyToManyField多个模型之间的关系 [英] ManyToManyField Relationships Between Multiple Models
问题描述
ManyToManyField
类型将两个模型相互链接。 我可以使用Django管理员添加一个书
,并创建一个作者
。但是当我查看作者
时,我刚刚创建它没有链接到书
。我必须明确地设置作者
实例和书
实例之间的反向关系。
这是正是或者我可以做不同的事情吗?
Models.py
class Book(models.Model):
book_title = models.CharField(max_length = 255,blank = False)
authors = models.ManyToManyField ('作者',空白=真)
类作者(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)
您不需要两个 ManyToManyField
定义,因为模型类没有 ManyToManyField
通过相反的关系与另一个相关。请参阅: https://docs.djangoproject。 com / en / dev / topics / db / queries /#many-to-many-relationships
如果将两个模型类定义为: p>
class Book(models.Model):
book_title = models.CharField(max_length = 255,blank = False)
authors = models.ManyToManyField('Author',blank = True)
类作者(models.Model):
author_first_name = models.CharField(max_length = 255,blank = False)
author_last_name = models.CharField(max_length = 255,blank = False)
然后为任何作者
实例 a
, a.book_set.all()
由作者撰写(或共同撰写)的书籍组成。
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).
这篇关于ManyToManyField多个模型之间的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!