| 1 | """
|
|---|
| 2 | 11. Relating an object to itself, many-to-one
|
|---|
| 3 |
|
|---|
| 4 | To define a many-to-one relationship between a model and itself, use
|
|---|
| 5 | ``ForeignKey('self')``.
|
|---|
| 6 |
|
|---|
| 7 | In this example, a ``Category`` is related to itself. That is, each
|
|---|
| 8 | ``Category`` has a parent ``Category``.
|
|---|
| 9 |
|
|---|
| 10 | Set ``related_name`` to designate what the reverse relationship is called.
|
|---|
| 11 | """
|
|---|
| 12 |
|
|---|
| 13 | from django.db import models
|
|---|
| 14 |
|
|---|
| 15 | class 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 |
|
|---|
| 22 | class 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 |
|
|---|
| 29 | API_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')
|
|---|
| 39 | Child category
|
|---|
| 40 | >>> print r.parent
|
|---|
| 41 | None
|
|---|
| 42 |
|
|---|
| 43 | >>> c.child_set.all()
|
|---|
| 44 | []
|
|---|
| 45 | >>> c.parent
|
|---|
| 46 | Root category
|
|---|
| 47 |
|
|---|
| 48 | >>> Category.AddManipulator().save(dict(id='3', name='Another root category', parent=None))
|
|---|
| 49 | Another root category
|
|---|
| 50 |
|
|---|
| 51 | >>> anotherone = Another.AddManipulator().save(dict(id='3', name='Another root category', another=None))
|
|---|
| 52 | Another root category
|
|---|
| 53 | """
|
|---|