~kkubasik/django/aggregation-branch

« back to all changes in this revision

Viewing changes to tests/testapp/models/m2m_intermediary.py

  • Committer: adrian
  • Date: 2006-05-02 01:31:56 UTC
  • Revision ID: vcs-imports@canonical.com-20060502013156-2941fcd40d080649
MERGED MAGIC-REMOVAL BRANCH TO TRUNK. This change is highly backwards-incompatible. Please read http://code.djangoproject.com/wiki/RemovingTheMagic for upgrade instructions.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
"""
2
 
9. Many-to-many relationships via an intermediary table
3
 
 
4
 
For many-to-many relationships that need extra fields on the intermediary
5
 
table, use an intermediary model.
6
 
 
7
 
In this example, an ``Article`` can have multiple ``Reporter``s, and each
8
 
``Article``-``Reporter`` combination (a ``Writer``) has a ``position`` field,
9
 
which specifies the ``Reporter``'s position for the given article (e.g. "Staff
10
 
writer").
11
 
"""
12
 
 
13
 
from django.core import meta
14
 
 
15
 
class Reporter(meta.Model):
16
 
    first_name = meta.CharField(maxlength=30)
17
 
    last_name = meta.CharField(maxlength=30)
18
 
 
19
 
    def __repr__(self):
20
 
        return "%s %s" % (self.first_name, self.last_name)
21
 
 
22
 
class Article(meta.Model):
23
 
    headline = meta.CharField(maxlength=100)
24
 
    pub_date = meta.DateField()
25
 
 
26
 
    def __repr__(self):
27
 
        return self.headline
28
 
 
29
 
class Writer(meta.Model):
30
 
    reporter = meta.ForeignKey(Reporter)
31
 
    article = meta.ForeignKey(Article)
32
 
    position = meta.CharField(maxlength=100)
33
 
 
34
 
    def __repr__(self):
35
 
        return '%r (%s)' % (self.get_reporter(), self.position)
36
 
 
37
 
API_TESTS = """
38
 
# Create a few Reporters.
39
 
>>> r1 = reporters.Reporter(first_name='John', last_name='Smith')
40
 
>>> r1.save()
41
 
>>> r2 = reporters.Reporter(first_name='Jane', last_name='Doe')
42
 
>>> r2.save()
43
 
 
44
 
# Create an Article.
45
 
>>> from datetime import datetime
46
 
>>> a = articles.Article(headline='This is a test', pub_date=datetime(2005, 7, 27))
47
 
>>> a.save()
48
 
 
49
 
# Create a few Writers.
50
 
>>> w1 = writers.Writer(reporter=r1, article=a, position='Main writer')
51
 
>>> w1.save()
52
 
>>> w2 = writers.Writer(reporter=r2, article=a, position='Contributor')
53
 
>>> w2.save()
54
 
 
55
 
# Play around with the API.
56
 
>>> a.get_writer_list(order_by=['-position'], select_related=True)
57
 
[John Smith (Main writer), Jane Doe (Contributor)]
58
 
>>> w1.get_reporter()
59
 
John Smith
60
 
>>> w2.get_reporter()
61
 
Jane Doe
62
 
>>> w1.get_article()
63
 
This is a test
64
 
>>> w2.get_article()
65
 
This is a test
66
 
>>> r1.get_writer_list()
67
 
[John Smith (Main writer)]
68
 
"""