2006-05-02 01:31:56 +00:00
|
|
|
"""
|
2014-09-24 05:13:13 +00:00
|
|
|
Relating an object to itself, many-to-one
|
2006-05-02 01:31:56 +00:00
|
|
|
|
|
|
|
To define a many-to-one relationship between a model and itself, use
|
2015-07-22 14:43:21 +00:00
|
|
|
``ForeignKey('self', ...)``.
|
2006-05-02 01:31:56 +00:00
|
|
|
|
|
|
|
In this example, a ``Category`` is related to itself. That is, each
|
|
|
|
``Category`` has a parent ``Category``.
|
|
|
|
|
|
|
|
Set ``related_name`` to designate what the reverse relationship is called.
|
|
|
|
"""
|
|
|
|
|
|
|
|
from django.db import models
|
2012-08-12 10:32:08 +00:00
|
|
|
from django.utils.encoding import python_2_unicode_compatible
|
2006-05-02 01:31:56 +00:00
|
|
|
|
2011-10-13 18:04:12 +00:00
|
|
|
|
2012-08-12 10:32:08 +00:00
|
|
|
@python_2_unicode_compatible
|
2006-05-02 01:31:56 +00:00
|
|
|
class Category(models.Model):
|
2007-08-05 05:14:46 +00:00
|
|
|
name = models.CharField(max_length=20)
|
2015-07-22 14:43:21 +00:00
|
|
|
parent = models.ForeignKey('self', models.SET_NULL, blank=True, null=True, related_name='child_set')
|
2006-05-02 01:31:56 +00:00
|
|
|
|
2012-08-12 10:32:08 +00:00
|
|
|
def __str__(self):
|
2006-05-02 01:31:56 +00:00
|
|
|
return self.name
|
|
|
|
|
2013-11-03 04:36:09 +00:00
|
|
|
|
2012-08-12 10:32:08 +00:00
|
|
|
@python_2_unicode_compatible
|
2010-10-12 00:14:49 +00:00
|
|
|
class Person(models.Model):
|
|
|
|
full_name = models.CharField(max_length=20)
|
2015-07-22 14:43:21 +00:00
|
|
|
mother = models.ForeignKey('self', models.SET_NULL, null=True, related_name='mothers_child_set')
|
|
|
|
father = models.ForeignKey('self', models.SET_NULL, null=True, related_name='fathers_child_set')
|
2010-10-12 00:14:49 +00:00
|
|
|
|
2012-08-12 10:32:08 +00:00
|
|
|
def __str__(self):
|
2010-10-12 00:14:49 +00:00
|
|
|
return self.full_name
|