Django

Code

root/django/trunk/tests/modeltests/m2o_recursive/models.py

Revision 7015, 1.0 kB (checked in by gwilson, 9 months ago)

Fixed #6365 -- Added blank=True to parent attribute of m2o_recursive model example, thanks dgrant.

  • Property svn:eol-style set to native
Line 
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(max_length=20)
17     parent = models.ForeignKey('self', blank=True, null=True, related_name='child_set')
18
19     def __unicode__(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 """}
Note: See TracBrowser for help on using the browser.