File: models.py

package info (click to toggle)
python-django 1.2.3-3%2Bsqueeze10
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 29,064 kB
  • ctags: 20,458
  • sloc: python: 101,293; xml: 574; makefile: 149; sh: 121; sql: 7
file content (91 lines) | stat: -rw-r--r-- 1,973 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
from django.db import models

class Publisher(models.Model):
    name = models.CharField(max_length=100)

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    name = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author, related_name='books')
    publisher = models.ForeignKey(Publisher, related_name='books')


__test__ = {'one':"""
#
# RelatedManager
#

# First create a Publisher.
>>> p = Publisher.objects.create(name='Acme Publishing')

# Create a book through the publisher.
>>> book, created = p.books.get_or_create(name='The Book of Ed & Fred')
>>> created
True

# The publisher should have one book.
>>> p.books.count()
1

# Try get_or_create again, this time nothing should be created.
>>> book, created = p.books.get_or_create(name='The Book of Ed & Fred')
>>> created
False

# And the publisher should still have one book.
>>> p.books.count()
1

#
# ManyRelatedManager
#

# Add an author to the book.
>>> ed, created = book.authors.get_or_create(name='Ed')
>>> created
True

# Book should have one author.
>>> book.authors.count()
1

# Try get_or_create again, this time nothing should be created.
>>> ed, created = book.authors.get_or_create(name='Ed')
>>> created
False

# And the book should still have one author.
>>> book.authors.count()
1

# Add a second author to the book.
>>> fred, created = book.authors.get_or_create(name='Fred')
>>> created
True

# The book should have two authors now.
>>> book.authors.count()
2

# Create an Author not tied to any books.
>>> Author.objects.create(name='Ted')
<Author: Author object>

# There should be three Authors in total. The book object should have two.
>>> Author.objects.count()
3
>>> book.authors.count()
2

# Try creating a book through an author.
>>> ed.books.get_or_create(name="Ed's Recipies", publisher=p)
(<Book: Book object>, True)

# Now Ed has two Books, Fred just one.
>>> ed.books.count()
2
>>> fred.books.count()
1
"""}