python Django 1.7 中文入门 (官网) 06 第一个项目1_2

在这一节主要讲应用的创建和models设置,这里非常重要,一定要认真学习哦。

工具/原料

  • python3.4.2
  • django1.7.1

方法/步骤

  1. 创建app

    D:\python\www\mysite>python3 manage.py startapp polls

    应用polls的目录如下:

    polls/

       __init__.py

       admin.py

       migrations/

           __init__.py

       models.py

       tests.py

       views.py

  2. 编辑poll/models.py文件

    from django.db import models

    # Create your models here.

    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)

            choice_text = models.CharField(max_length=200)

            votes = models.IntegerField(default=0)

  3. 激活models

    编辑mysite/settings.py,添加polls应用。

    INSTALLED_APPS = (

       'django.contrib.admin',

       'django.contrib.auth',

       'django.contrib.contenttypes',

       'django.contrib.sessions',

       'django.contrib.messages',

       'django.contrib.staticfiles',

       'polls'

    )

  4. 现在Django已经知道项目包括polls应用,运行如下命令:

    D:\python\www\mysite>manage.py makemigrations polls

    然后显示如下内容:

    Migrations for 'polls':

     0001_initial.py:

       - Create model Choice

       - Create model Question

       - Add field question to choice

  5. 运行sqlmigrate命令可以返回SQL语句:

    python3 manage.py sqlmigrate polls 0001

    返回如下:

    BEGIN;

    CREATE TABLE "polls_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);

    CREATE TABLE "polls_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,

    "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);

    CREATE TABLE "polls_choice__new" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id"

    integer NOT NULL REFERENCES "polls_question" ("id"));

    INSERT INTO "polls_choice__new" ("id", "choice_text", "votes") SELECT "id", "cho

    ice_text", "votes" FROM "polls_choice";

    DROP TABLE "polls_choice";

    ALTER TABLE "polls_choice__new" RENAME TO "polls_choice";

    CREATE INDEX polls_choice_7aa0f6ee ON "polls_choice" ("question_id");

    COMMIT;

  6. 现在运行migrate创建models表格。

    python3 manage.py migrate

    返回:

    Operations to perform:

     Apply all migrations: admin, auth, sessions, polls, contenttypes

    Running migrations:

     Applying polls.0001_initial... OK

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值