Skip to content Skip to sidebar Skip to footer

Django Models That Contains List Of Another Model

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

Solution 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.

Post a Comment for "Django Models That Contains List Of Another Model"