Monday, October 13, 2008

Django Model Many-to-One

Define the models

from django.db import models

class Reporter(models.Model):
.. first_name = models.CharField(max_length=30)
.. last_name = models.CharField(max_length=30)
.. email = models.EmailField(blank=True, null=True)

def __unicode__(self):
.. return u"%s %s" % (self.first_name, self.last_name)

class Article(models.Model):
.. headline = models.CharField(max_length=100)
.. pub_date = models.DateField()
.. reporter = models.ForeignKey(Reporter, blank=True, null=True)

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

.. class Meta:
.... ordering = ('headline',)
------------------------------------------------
Add some objects

# import models from core.models
>>> from core.models import Reporter, Article
>>> from datetime import datetime # needed for inserting current time
# add some reporters

>>> r1 = Reporter(first_name="Joe", last_name="Jaz")
>>> r1.save()
>>> r2 = Reporter(first_name="Jane", last_name="Smith")
>>> r2.save()
# add some articles
>>> a1 = Article(headline="Article1", pub_date=datetime(2008,10,14))
>>> a1.reporter = r1 # can add separately
>>> a1.save()
>>> a2 = Article(headline="Article2", pub_date=datetime(2008,10,15), reporter=r2)
>>> a2.save()
# show an article's reporter
>>> a1.reporter

<Reporter: Joe Jaz>
>>> a2.reporter.first_name
'Jane'
# create an article "under" a Reporter via the Reporter object
# the 'article_set' method is generated on model creation using the lower-case model name
# the create method automatically does a save()
>>> a3 = r1.article_set.create(headline="Article3", pub_date=datetime.now())
>>> a3.headline
'Article3'
>>> a3

<Article: Article1>
# returns object with Article type
>>> a3.reporter
<Reporter: Joe Jaz> # returns object with Reporter type - the article reporter
# create an article with no reporter and then add it to a particular reporters set of articles
# the add method automatically does a save()
>>> a4 = Article(headline="Article4", pub_date=datetime.now())
>>> r2.article_set.add(a4)
# show all of the given reporter's articles
>>> r2.article_set.all()
[<Article: Article2>, <Article: Article4>]
# count the number of articles that belong to a reporter
>>> r2.record_set.count()
2
>>> r1.record_set.count()
2
# associate article 4 with reporter 1 (instead of reporter 2)
>>> r1.article_set.add(a4)
# we can assign it back and use different syntax this time
>>> a4.reporter = r2
>>> a4.save()
# we can assign multiple articles to a reporter at a time
# this syntax calls save automatically
>>> r1.article_set = [a2, a4]
# we can create an article and assign it with a reporter_id instead of the reporter object
# the reporter_id field is generated with the model
>>> a5 = Article(headline="Article5",pub_date=datetime.now(),reporter_id=r1.id)
>>> a5.save()
# or reporter_id can be a string
>>> a6 = Article(headline="Article6",pub_date=datetime.now(), reporter_id="1")
>>> a6.save()
# Do a query to find reporters of article 1 and article 3
>>> Reporter.objects.filter(article__in=[a1,a3])

http://www.djangoproject.com/documentation/models/many_to_one/

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)

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