Ticket #1839: models.py

File models.py, 1.4 KB (added by mir@…, 19 years ago)

unit test demonstrating this problem

Line 
1"""
211. Relating an object to itself, many-to-one
3
4To define a many-to-one relationship between a model and itself, use
5``ForeignKey('self')``.
6
7In this example, a ``Category`` is related to itself. That is, each
8``Category`` has a parent ``Category``.
9
10Set ``related_name`` to designate what the reverse relationship is called.
11"""
12
13from django.db import models
14
15class Category(models.Model):
16 name = models.CharField(maxlength=20)
17 parent = models.ForeignKey('self', null=True, related_name='child_set')
18
19 def __repr__(self):
20 return self.name
21
22class Another(models.Model):
23 name = models.CharField(maxlength=20, core=True)
24 another = models.ForeignKey('self', null=True, related_name='child_set')
25
26 def __repr__(self):
27 return self.name
28
29API_TESTS = """
30# Create a few Category objects.
31>>> r = Category(id=None, name='Root category', parent=None)
32>>> r.save()
33>>> c = Category(id=None, name='Child category', parent=r)
34>>> c.save()
35
36>>> r.child_set.all()
37[Child category]
38>>> r.child_set.get(name__startswith='Child')
39Child category
40>>> print r.parent
41None
42
43>>> c.child_set.all()
44[]
45>>> c.parent
46Root category
47
48>>> Category.AddManipulator().save(dict(id='3', name='Another root category', parent=None))
49Another root category
50
51>>> anotherone = Another.AddManipulator().save(dict(id='3', name='Another root category', another=None))
52Another root category
53"""
Back to Top