Ticket #7526: models.py

File models.py, 1.7 KB (added by khoobks, 11 years ago)

Test case illustrating the issue.

Line 
1"""
24. Many-to-one relationships
3
4To define a many-to-one relationship, use ``ForeignKey()`` .
5"""
6
7from django.db import models
8
9class Reporter(models.Model):
10    first_name = models.CharField(max_length=30)
11    last_name = models.CharField(max_length=30)
12    email = models.EmailField()
13
14    def __unicode__(self):
15        return u"%s %s" % (self.first_name, self.last_name)
16
17class Subject(models.Model):
18    first_name = models.CharField(max_length=30)
19    last_name = models.CharField(max_length=30)
20    email = models.EmailField()
21
22    def __unicode__(self):
23        return u"%s %s" % (self.first_name, self.last_name)
24
25class Article(models.Model):
26    headline = models.CharField(max_length=100)
27    pub_date = models.DateField()
28    reporter = models.ForeignKey(Reporter, core=True, null=True, blank=True)
29    subject = models.ForeignKey(Subject, core=True, null=True, blank=True)
30
31    def __unicode__(self):
32        return self.headline
33
34    class Meta:
35        ordering = ('reporter__last_name','subject__last_name')
36
37__test__ = {'API_TESTS':"""
38# Create a few Reporters.
39>>> r = Reporter(first_name='John', last_name='Smith', email='john@example.com')
40>>> r.save()
41
42>>> r2 = Reporter(first_name='Paul', last_name='Jones', email='paul@example.com')
43>>> r2.save()
44
45# Create an Article.
46>>> from datetime import datetime
47>>> a = Article(id=None, headline="This is a test", pub_date=datetime(2005, 7, 27), reporter=r)
48>>> a.save()
49
50>>> len(Article.objects.all())
511
52
53>>> Article.objects.all().count()
541
55
56>>> Article.objects.filter(subject=None)
57[<Article: This is a test>]
58
59# Alternative syntax
60>>> Article.objects.filter(subject__isnull=True)
61[<Article: This is a test>]
62
63
64"""}
Back to Top