Django project #3: Creating models



This is my OLD blog. I've copied this post over to my NEW blog at:

http://www.saltycrane.com/blog/2007/11/django-project-3-creating-models/

You should be redirected in 2 seconds.



This section in the tutorial was actually very straightforward. Here is a record of what I did. I first created a polls app.

sofeng@tortoise:~/Web/mysite$ python manage.py startapp polls
sofeng@tortoise:~/Web/mysite$ ll
total 92
-rw-r--r-- 1     0 2007 11/09 21:42 __init__.py
-rw-r--r-- 1   131 2007 11/09 21:56 __init__.pyc
-rwxr-xr-x 1   542 2007 11/09 21:42 manage.py
-rw-r--r-- 1 35840 2007 11/28 23:07 mydb
-rw-r--r-- 1 25600 2007 11/14 23:13 mydb_backup
drwxr-xr-x 2  4096 2007 11/28 23:15 polls
-rw-r--r-- 1  2886 2007 11/28 22:41 settings.py
-rw-r--r-- 1  1873 2007 11/28 22:42 settings.pyc
-rw-r--r-- 1   224 2007 11/28 22:44 urls.py
-rw-r--r-- 1   302 2007 11/28 22:45 urls.pyc
sofeng@tortoise:~/Web/mysite$ ll polls
total 8
-rw-r--r-- 1  0 2007 11/28 23:15 __init__.py
-rw-r--r-- 1 57 2007 11/28 23:15 models.py
-rw-r--r-- 1 26 2007 11/28 23:15 views.py
I entered the following into polls/models.py
from django.db import models

class Poll(models.Model):
    question = models.CharField(maxlength=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(maxlength=200)
    votes = models.IntegerField()
I edited settings.py to include the new app:
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'mysite.polls',
)
I ran python manage.py sql polls to see the SQL CREATE TABLE statements for the polls app.
sofeng@tortoise:~/Web/mysite$ python manage.py sql polls
BEGIN;
CREATE TABLE "polls_poll" (
    "id" integer NOT NULL PRIMARY KEY,
    "question" varchar(200) NOT NULL,
    "pub_date" datetime NOT NULL
);
CREATE TABLE "polls_choice" (
    "id" integer NOT NULL PRIMARY KEY,
    "poll_id" integer NOT NULL REFERENCES "polls_poll" ("id"),
    "choice" varchar(200) NOT NULL,
    "votes" integer NOT NULL
);
COMMIT;
I ran python manage.py syncdb to create the model tables in the database.
sofeng@tortoise:~/Web/mysite$ python manage.py syncdb
Creating table polls_poll
Creating table polls_choice
Installing index for polls.Choice model
Loading 'initial_data' fixtures...
No fixtures found.
I played with the shell.
sofeng@tortoise:~/Web/mysite$ python manage.py shell
Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32) 
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from mysite.polls.models import Poll, Choice
>>> Poll.objects.all()
[]
>>> from datetime import datetime
>>> p = Poll(question="What's up?", pub_date=datetime.now())
>>> p.save()
>>> p.id
1
>>> p.question
"What's up?"
>>> p.pub_date
datetime.datetime(2007, 11, 29, 1, 34, 4, 883118)
>>> p.pub_date = datetime(2005, 4, 1, 0, 0)
>>> p.save()
>>> Poll.objects.all()
[]
>>> 
I edited polls/models.py so that it looked like this:
import datetime
from django.db import models

class Poll(models.Model):
    question = models.CharField(maxlength=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question

    def was_published_today(self):
        return self.pub_date.date() == datetime.date.today()

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(maxlength=200)
    votes = models.IntegerField()

    def __str__(self):
        return self.choice
I went back to the shell.
sofeng@tortoise:~/Web/mysite$ python manage.py shell
Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32) 
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from mysite.polls.models import Poll, Choice
>>> Poll.objects.all()
[<Poll: What's up?>]
>>> Poll.objects.filter(id=1)
[<Poll: What's up?>]
>>> Poll.objects.filter(question__startswith='What')
[<Poll: What's up?>]
>>> Poll.objects.get(pub_date__year=2005)
<Poll: What's up?>
>>> Poll.objects.get(id=2)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/var/lib/python-support/python2.5/django/db/models/manager.py", line 73, in get
    return self.get_query_set().get(*args, **kwargs)
  File "/var/lib/python-support/python2.5/django/db/models/query.py", line 252, in get
    raise self.model.DoesNotExist, "%s matching query does not exist." % self.model._meta.object_name
DoesNotExist: Poll matching query does not exist.
>>> Poll.objects.get(pk=1)
<Poll: What's up?>
>>> p = Poll.objects.get(pk=1)
>>> p.was_published_today()
False
>>> p = Poll.objects.get(pk=1)
>>> p.choice_set.create(choice='Not much', votes=0)
<Choice: Not much>
>>> p.choice_set.create(choice='The sky', votes=0)
<Choice: The sky>
>>> c = p.choice_set.create(choice='Just hacking again', votes=0)
>>> c.poll
<Poll: What's up?>
>>> p.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> p.choice_set.count()
3
>>> Choice.objects.filter(poll__pub_date__year=2005)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> c = p.choice_set.filter(choice__startswith='Just hacking')
>>> c.delete()
>>> 
That's it for now. Next time I will work with Django's admin web interface.

No comments:

About

This is my *OLD* blog. I've copied all of my posts and comments over to my NEW blog at:

http://www.saltycrane.com/blog/.

Please go there for my updated posts. I will leave this blog up for a short time, but eventually plan to delete it. Thanks for reading.