thirdparty/google_appengine/lib/django/tests/modeltests/m2o_recursive/models.py
changeset 2866 a04b1e4126c4
parent 2864 2e0b0af889be
child 2868 9f7f269383f7
equal deleted inserted replaced
2864:2e0b0af889be 2866:a04b1e4126c4
     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 __str__(self):
       
    20         return self.name
       
    21 
       
    22 __test__ = {'API_TESTS':"""
       
    23 # Create a few Category objects.
       
    24 >>> r = Category(id=None, name='Root category', parent=None)
       
    25 >>> r.save()
       
    26 >>> c = Category(id=None, name='Child category', parent=r)
       
    27 >>> c.save()
       
    28 
       
    29 >>> r.child_set.all()
       
    30 [<Category: Child category>]
       
    31 >>> r.child_set.get(name__startswith='Child')
       
    32 <Category: Child category>
       
    33 >>> print r.parent
       
    34 None
       
    35 
       
    36 >>> c.child_set.all()
       
    37 []
       
    38 >>> c.parent
       
    39 <Category: Root category>
       
    40 """}