Problem statement
Books, authors and publishers are stored in unrelated tables, so nothing connects a book to who wrote it or who published it. Your task is to relate the models in app/models.py, choosing the relationship type and what happens on delete for each link.
Existing Models
app/models.py already defines three models:
| Model | Field | Meaning |
|---|---|---|
| Author | name | text, at most 200 characters |
| Publisher | name | text, at most 200 characters |
| Book | title | text, at most 200 characters |
Book has no link to Author or Publisher yet. Those links are what you add, at the # Write your code here marker in Book.
Requirements
- Every book has exactly one author; an author can have many books. Add an author field to Book. It is required: saving a Book without an author must be rejected (by the database or by Django).
- An author's books go with the author. Deleting an Author deletes that author's books too, and leaves other authors' books untouched.
- An author's books are reachable as author.books. author.books.all() returns that author's books, and the relation must also work in queries that go from author to book, for example Author.objects.filter(books__title="The Hobbit"). The Django default name (author.book_set) must not exist. A hand-written books property does not count: the name has to belong to the relationship itself.
- A book may have a publisher, and a publisher with books cannot be deleted. Add a publisher field to Book. It is optional: a book with no publisher (publisher=None) saves fine. Each book has at most one publisher; a publisher can have many books. Deleting a Publisher that still has at least one book must be refused with Django's ProtectedError, and the publisher and its books must stay in the database. A publisher with no books deletes normally.
Sample Usage
>>> rowling = Author.objects.create(name="J. K. Rowling")
>>> stone = Book.objects.create(title="Philosopher's Stone", author=rowling)
>>> stone.author.name
'J. K. Rowling'
>>> list(rowling.books.values_list("title", flat=True))
["Philosopher's Stone"]
>>> list(Author.objects.filter(books__title="Philosopher's Stone"))
[<Author: J. K. Rowling>]
>>> rowling.delete()
>>> Book.objects.count()
0
>>> penguin = Publisher.objects.create(name="Penguin")
>>> tolkien = Author.objects.create(name="J. R. R. Tolkien")
>>> Book.objects.create(title="The Hobbit", author=tolkien, publisher=penguin)
<Book: The Hobbit>
>>> penguin.delete()
django.db.models.deletion.ProtectedError: ...
