django系列3 :创建模型

1创建模型

在我们简单的民意调查应用程序中,我们将创建两个模型:QuestionChoiceQuestion有问题和出版日期。Choice有两个字段:选择的文本和投票记录。每个Choice都与一个Question

这些概念由简单的Python类表示。编辑 polls/models.py文件,使其如下所示:

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

 这里的choice和question是多对一的关系,所以choice里面有一个ForeignKey,关联了question.

 这里的CASCADE,是如果question表中的记录被删除,则choice表中对应的记录自动被删除

猜你喜欢

转载自www.cnblogs.com/zhizhiyin/p/9706104.html
今日推荐