import datetime
from django.db import models
from django.utils import timezone
# Create your models here.
class Poll(models.Model):
def __unicode__(self):
return self.question
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Question(models.Model):
def __unicode__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
def __unicode__(self):
return self.choice_text
poll = models.ForeignKey(Poll)
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
And the corresponding mysql database tables are
mysql> desc polls_poll;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| question | varchar(200) | NO | | NULL | |
| pub_date | datetime | NO | | NULL | |
+----------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
mysql> desc polls_question;
+---------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| question_text | varchar(200) | NO | | NULL | |
| pub_date | datetime | NO | | NULL | |
+---------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
mysql> desc polls_choice;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| choice_text | varchar(200) | NO | | NULL | |
| votes | int(11) | NO | | NULL | |
| poll_id | int(11) | NO | MUL | NULL | |
| question_id | int(11) | NO | MUL | NULL | |
+-------------+--------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
This tutorial doesn't ask to create poll record, and since question is not modeled related to poll, so I can create and save a question record without poll.
These seem a bit strange, but let's just create a poll record to move on.
It turns out that's not the case:
>>> q.choice_set.create(choice_text='Not much', votes=0)
Cause the exception because
(1) the statement does not contain poll_id value
(2) the statement excutes the database insertion implicitly
(3) the table polls_choice column was set not null.
My guess is that the tutorial is out of sync with the changes of django....
So what's the best doc for learning django?