~kkubasik/django/aggregation-branch

« back to all changes in this revision

Viewing changes to tests/testapp/models/many_to_one_null.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
 
16. Many-to-one relationships that can be null
3
 
 
4
 
To define a many-to-one relationship that can have a null foreign key, use
5
 
``ForeignKey()`` with ``null=True`` .
6
 
"""
7
 
 
8
 
from django.core import meta
9
 
 
10
 
class Reporter(meta.Model):
11
 
    name = meta.CharField(maxlength=30)
12
 
 
13
 
    def __repr__(self):
14
 
        return self.name
15
 
 
16
 
class Article(meta.Model):
17
 
    headline = meta.CharField(maxlength=100)
18
 
    reporter = meta.ForeignKey(Reporter, null=True)
19
 
 
20
 
    def __repr__(self):
21
 
        return self.headline
22
 
 
23
 
API_TESTS = """
24
 
# Create a Reporter.
25
 
>>> r = reporters.Reporter(name='John Smith')
26
 
>>> r.save()
27
 
 
28
 
# Create an Article.
29
 
>>> a = articles.Article(headline="First", reporter=r)
30
 
>>> a.save()
31
 
 
32
 
>>> a.reporter_id
33
 
1
34
 
 
35
 
>>> a.get_reporter()
36
 
John Smith
37
 
 
38
 
# Article objects have access to their related Reporter objects.
39
 
>>> r = a.get_reporter()
40
 
 
41
 
# Create an Article via the Reporter object.
42
 
>>> a2 = r.add_article(headline="Second")
43
 
>>> a2
44
 
Second
45
 
>>> a2.reporter_id
46
 
1
47
 
 
48
 
# Reporter objects have access to their related Article objects.
49
 
>>> r.get_article_list(order_by=['headline'])
50
 
[First, Second]
51
 
>>> r.get_article(headline__startswith='Fir')
52
 
First
53
 
>>> r.get_article_count()
54
 
2
55
 
 
56
 
# Create an Article with no Reporter by passing "reporter=None".
57
 
>>> a3 = articles.Article(headline="Third", reporter=None)
58
 
>>> a3.save()
59
 
>>> a3.id
60
 
3
61
 
>>> a3.reporter_id
62
 
>>> print a3.reporter_id
63
 
None
64
 
>>> a3 = articles.get_object(pk=3)
65
 
>>> print a3.reporter_id
66
 
None
67
 
 
68
 
# An article's get_reporter() method throws ReporterDoesNotExist
69
 
# if the reporter is set to None.
70
 
>>> a3.get_reporter()
71
 
Traceback (most recent call last):
72
 
    ...
73
 
ReporterDoesNotExist
74
 
 
75
 
# To retrieve the articles with no reporters set, use "reporter__isnull=True".
76
 
>>> articles.get_list(reporter__isnull=True)
77
 
[Third]
78
 
"""