2
16. Many-to-one relationships that can be null
4
To define a many-to-one relationship that can have a null foreign key, use
5
``ForeignKey()`` with ``null=True`` .
8
from django.core import meta
10
class Reporter(meta.Model):
11
name = meta.CharField(maxlength=30)
16
class Article(meta.Model):
17
headline = meta.CharField(maxlength=100)
18
reporter = meta.ForeignKey(Reporter, null=True)
25
>>> r = reporters.Reporter(name='John Smith')
29
>>> a = articles.Article(headline="First", reporter=r)
38
# Article objects have access to their related Reporter objects.
39
>>> r = a.get_reporter()
41
# Create an Article via the Reporter object.
42
>>> a2 = r.add_article(headline="Second")
48
# Reporter objects have access to their related Article objects.
49
>>> r.get_article_list(order_by=['headline'])
51
>>> r.get_article(headline__startswith='Fir')
53
>>> r.get_article_count()
56
# Create an Article with no Reporter by passing "reporter=None".
57
>>> a3 = articles.Article(headline="Third", reporter=None)
62
>>> print a3.reporter_id
64
>>> a3 = articles.get_object(pk=3)
65
>>> print a3.reporter_id
68
# An article's get_reporter() method throws ReporterDoesNotExist
69
# if the reporter is set to None.
71
Traceback (most recent call last):
75
# To retrieve the articles with no reporters set, use "reporter__isnull=True".
76
>>> articles.get_list(reporter__isnull=True)