1
from django.db import models
3
class Publisher(models.Model):
4
name = models.CharField(max_length=100)
6
class Author(models.Model):
7
name = models.CharField(max_length=100)
9
class Book(models.Model):
10
name = models.CharField(max_length=100)
11
authors = models.ManyToManyField(Author, related_name='books')
12
publisher = models.ForeignKey(Publisher, related_name='books')
20
# First create a Publisher.
21
>>> p = Publisher.objects.create(name='Acme Publishing')
23
# Create a book through the publisher.
24
>>> book, created = p.books.get_or_create(name='The Book of Ed & Fred')
28
# The publisher should have one book.
32
# Try get_or_create again, this time nothing should be created.
33
>>> book, created = p.books.get_or_create(name='The Book of Ed & Fred')
37
# And the publisher should still have one book.
45
# Add an author to the book.
46
>>> ed, created = book.authors.get_or_create(name='Ed')
50
# Book should have one author.
51
>>> book.authors.count()
54
# Try get_or_create again, this time nothing should be created.
55
>>> ed, created = book.authors.get_or_create(name='Ed')
59
# And the book should still have one author.
60
>>> book.authors.count()
63
# Add a second author to the book.
64
>>> fred, created = book.authors.get_or_create(name='Fred')
68
# The book should have two authors now.
69
>>> book.authors.count()
72
# Create an Author not tied to any books.
73
>>> Author.objects.create(name='Ted')
74
<Author: Author object>
76
# There should be three Authors in total. The book object should have two.
77
>>> Author.objects.count()
79
>>> book.authors.count()
82
# Try creating a book through an author.
83
>>> ed.books.get_or_create(name="Ed's Recipies", publisher=p)
84
(<Book: Book object>, True)
86
# Now Ed has two Books, Fred just one.
89
>>> fred.books.count()