Django创建模型

在Django中写一个数据库驱动的Web应用的第一步是定义模型,这是数据库结构设计和附加的其他元数据。
在投票应用中,将创建Question(问题)和Choice(选项)两个模型,Question模型包括问题描述和发布时间,Choice模型包括选项描述和当前得票数。每个选项属于一个问题。
重写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)

question_text、pub_date是字段名,CharField、DateTimeField是字段数据类型

修改mysite\settings.py

INSTALLED_APPS = [
    'polls.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

为模型的修改生成迁移文件:

(django-env) D:\Django Projects\mysite>python manage.py makemigrations polls
Migrations for 'polls':
  polls\migrations\0001_initial.py
    - Create model Question
    - Create model Choice

通过运行makemigrations命令,Django会检测对模型的修改并将修改的部分储存为一次迁移。migrations(迁移)是Django对于模型定义(数据库结构)的变化的储存形式。

查看模型修改对应的SQL语句:

(django-env) D:\Django Projects\mysite>python manage.py sqlmigrate polls 0001
--
-- Create model Question
--
CREATE TABLE `polls_question` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `question_text` varchar(200) NOT NULL, `pub_date` datetime(6) NOT NULL);
--
-- Create model Choice
--
CREATE TABLE `polls_choice` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `choice_text` varchar(200) NOT NULL, `votes` integer NOT NULL, `question_id` integer NOT NULL);
ALTER TABLE `polls_choice` ADD CONSTRAINT `polls_choice_question_id_c5b4b260_fk_polls_question_id` FOREIGN KEY (`question_id`) REFERENCES `polls_question` (`id`);

应用数据库迁移:

(django-env) D:\Django Projects\mysite>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Applying polls.0001_initial... OK

你可能感兴趣的:(Django学习笔记,Python)