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
'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
# 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/