~ubuntu-branches/ubuntu/quantal/python-django/quantal

« back to all changes in this revision

Viewing changes to tests/modeltests/m2o_recursive/models.py

  • Committer: Bazaar Package Importer
  • Author(s): Chris Lamb
  • Date: 2009-07-29 11:26:28 UTC
  • mfrom: (1.1.8 upstream) (4.1.5 sid)
  • Revision ID: james.westby@ubuntu.com-20090729112628-pg09ino8sz0sj21t
Tags: 1.1-1
* New upstream release.
* Merge from experimental:
  - Ship FastCGI initscript and /etc/default file in python-django's examples
    directory (Closes: #538863)
  - Drop "05_10539-sphinx06-compatibility.diff"; it has been applied
    upstream.
  - Bump Standards-Version to 3.8.2.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
"""}