Sunday, October 12, 2008

Django OneToMany & ManyToMany Recursive Models

Define the models in core.models.

from django.db import models

class Place(models.Model):
.. name = models.CharField(max_length=50);
.. parent = models.ForeignKey('self', null=True);

.. def __unicode__(self):
.... return "%s > %s" % (self.name,self.parent )

class Fan(models.Model):
.. name = models.CharField(max_length=8)
.. idol = models.ManyToManyField('self', null=True)

.. def __unicode__(self):
.... return self.name

----------------------------------------------------------
Interact with a Foreign Key (One to Many)

# import Place model
from core.models import Place
# add a Place and save
world = Place(name="Earth", parent=None)
world.save()
# add two Places with the world as a parent
country1 = Place(name="US", parent=world)
country1.save()
country2 = Place(name="UK", parent=world)
country2.save()
# add two Places with the US as a parent
city1 = Place(name="Chicago")
city1.parent = country1 # make the association through an update
city1.save()
city2 = Place(name="New York", parent=country1) # associate through insert
city2.save()
# select all the places
Place.objects.all()

------------------------------------------------------
Interact with a Many to Many model

from core.models import
Fan

# Define 2 people
person1 =
Fan(name="Joe")
person1.save()
person2 = Fan(name="Jane")
person2.save()
# associate the two people
person1.idol.add(person2)

------------------------------------------------------

No comments: