django models that contains list of another model

百般思念 提交于 2021-02-10 11:50:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!