Django documentation

24. Mutually referential many-to-one relationships

This example describes Django version 0.96. For the current example, go here.

To define a many-to-one relationship, use ForeignKey() .

Model source code

from django.db.models import *

class Parent(Model):
    name = CharField(maxlength=100, core=True)
    bestchild = ForeignKey("Child", null=True, related_name="favoured_by")

class Child(Model):
    name = CharField(maxlength=100)
    parent = ForeignKey(Parent)

Sample API usage

This sample code assumes the above models have been saved in a file mysite/models.py.

>>> from mysite.models import 

# Create a Parent
>>> q = Parent(name='Elizabeth')
>>> q.save()

# Create some children
>>> c = q.child_set.create(name='Charles')
>>> e = q.child_set.create(name='Edward')

# Set the best child
>>> q.bestchild = c
>>> q.save()

>>> q.delete()