问题
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.
I have seen foreignKey, but It seems like that it only to hold one object.
回答1:
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.
If you intend for a book to be able to have more than one author, a ManyToManyField would be more appropriate.
To see all the books by a particular author, you'd want to use author.book_set.all()
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.
来源:https://stackoverflow.com/questions/18415130/django-models-that-contains-list-of-another-model