多对一关系 :
Django 使用django.db.models.ForeignKey 定义多对一关系,和使用其他字段类型一样,在模型当中把它作为一个类属性包含进来。
ForeignKey 需要一个位置参数:与该模型关联的类。
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self): # __unicode__ on Python 2
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self): # __unicode__ on Python 2
return self.choice_text
mysql> select * from polls_choice;
+----+-------------+-------+-------------+
| id | choice_text | votes | question_id |
+----+-------------+-------+-------------+
| 1 | 999999 | 7 | 1 |
| 2 | 88888 | 3 | 2 |
| 3 | 77777 | 6 | 1 |
+----+-------------+-------+-------------+
3 rows in set (0.00 sec)
mysql> select * from polls_question;
+----+---------------+----------------------------+
| id | question_text | pub_date |
+----+---------------+----------------------------+
| 1 | What's up? | 2018-07-13 02:01:34.356621 |
| 2 | aaaaaa | 2017-01-01 12:00:00.000000 |
| 3 | bbbbb | 2018-07-13 02:00:00.000000 |
+----+---------------+----------------------------+
3 rows in set (0.00 sec)
http://192.168.137.3:8000/polls/1/vote/
What's up?
You didn't select a choice.
999999
77777