2
11. Relating an object to itself, many-to-one
4
To define a many-to-one relationship between a model and itself, use
5
``ForeignKey('self')``.
7
In this example, a ``Category`` is related to itself. That is, each
8
``Category`` has a parent ``Category``.
10
Set ``related_name`` to designate what the reverse relationship is called.
13
from django.db import models
15
class Category(models.Model):
16
name = models.CharField(max_length=20)
17
parent = models.ForeignKey('self', blank=True, null=True, related_name='child_set')
19
def __unicode__(self):
22
__test__ = {'API_TESTS':"""
23
# Create a few Category objects.
24
>>> r = Category(id=None, name='Root category', parent=None)
26
>>> c = Category(id=None, name='Child category', parent=r)
30
[<Category: Child category>]
31
>>> r.child_set.get(name__startswith='Child')
32
<Category: Child category>
39
<Category: Root category>