2005-07-31 09:23:47 +08:00
|
|
|
"""
|
|
|
|
11. Relating an object to itself, many-to-one
|
|
|
|
|
|
|
|
To define a many-to-one relationship between a model and itself, use
|
|
|
|
``ForeignKey('self')``.
|
|
|
|
|
|
|
|
In this example, a ``Category`` is related to itself. That is, each
|
|
|
|
``Category`` has a parent ``Category``.
|
|
|
|
|
2005-08-26 06:51:30 +08:00
|
|
|
Set ``related_name`` to designate what the reverse relationship is called.
|
2005-07-31 09:23:47 +08:00
|
|
|
"""
|
|
|
|
|
2005-12-14 13:02:51 +08:00
|
|
|
from django.db import models
|
2005-07-31 09:23:47 +08:00
|
|
|
|
2005-12-14 13:02:51 +08:00
|
|
|
class Category(models.Model):
|
|
|
|
name = models.CharField(maxlength=20)
|
2006-02-04 06:31:56 +08:00
|
|
|
parent = models.ForeignKey('self', null=True, related_name='child_set')
|
2005-07-31 09:23:47 +08:00
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return self.name
|
|
|
|
|
|
|
|
API_TESTS = """
|
|
|
|
# Create a few Category objects.
|
2005-12-12 06:10:02 +08:00
|
|
|
>>> r = Category(id=None, name='Root category', parent=None)
|
2005-07-31 09:23:47 +08:00
|
|
|
>>> r.save()
|
2005-12-12 06:10:02 +08:00
|
|
|
>>> c = Category(id=None, name='Child category', parent=r)
|
2005-07-31 09:23:47 +08:00
|
|
|
>>> c.save()
|
|
|
|
|
2006-01-31 09:08:02 +08:00
|
|
|
>>> r.child_set.all()
|
2005-07-31 09:23:47 +08:00
|
|
|
[Child category]
|
2006-01-30 08:38:23 +08:00
|
|
|
>>> r.child_set.get(name__startswith='Child')
|
2005-07-31 09:23:47 +08:00
|
|
|
Child category
|
2006-01-30 08:38:23 +08:00
|
|
|
>>> r.parent
|
2005-07-31 09:23:47 +08:00
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2005-12-12 06:10:02 +08:00
|
|
|
DoesNotExist
|
2005-07-31 09:23:47 +08:00
|
|
|
|
2006-01-31 09:08:02 +08:00
|
|
|
>>> c.child_set.all()
|
2005-07-31 09:23:47 +08:00
|
|
|
[]
|
2006-01-30 08:38:23 +08:00
|
|
|
>>> c.parent
|
2005-07-31 09:23:47 +08:00
|
|
|
Root category
|
|
|
|
"""
|