问题描述
我正在尝试制作一个Django模型,该模型可以将另一个模型的列表作为属性
I am trying to make a django model that can have a list of another model as an attribute
def author:
name = charfield...
list_of_books = ______________
def book:
name = charfield...
我希望作者能够拥有他写过的书的清单.而且我想知道如何将一本书添加到作者列表中.
I want an author to be able to have a list of books he has written. And I would like to know how I can add a book to the authors list of books.
我看过foreignKey,但是看来它只能容纳一个对象.
I have seen foreignKey, but It seems like that it only to hold one object.
推荐答案
在另一个方向上使用ForeignKey.书籍应包含作者的ForeignKey,默认情况下,作者将包含成员book_set,该成员具有与该作者相关联的所有书籍的列表.
Use a ForeignKey in the other direction. book should contain a ForeignKey to author, and, by default, author will then contain the member book_set that has a list of all books that are associated with that author.
如果您打算让一本书拥有不止一位作者,那么ManyToManyField会更合适.
If you intend for a book to be able to have more than one author, a ManyToManyField would be more appropriate.
要查看特定作者的所有书籍,您需要使用author.book_set.all()
To see all the books by a particular author, you'd want to use author.book_set.all()
此页面包含使用图书,作者,和出版商之间,作者和书籍之间的关系表示为ManyToManyField.
This page contains an example of a database that uses books, authors, and publishers, where the relationship between authors and books is represented as a ManyToManyField.
这篇关于django模型,其中包含另一个模型的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!