创建模型

创建模型:

在这个简单的投票应用中,我们将创建两个模型:

Question 和Choice. Question 对象具有一个question_text(问题)属性 和一个 publish_date(发布时间)属性  


这些概念通过简单的Python类来表示。 编辑polls/models.py文件,并让它看起来像这样:

node1:/django/mysite/polls#cat models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

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, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
	
python manage.py makemigrations polls



node1:/django/mysite# python manage.py sqlmigrate polls 0001
CommandError: Cannot find a migration matching '0001' from app 'polls'. Is it in INSTALLED_APPS?
node1:/django/mysite#python manage.py makemigrations polls
Migrations for 'polls':
  polls/migrations/0001_initial.py
    - Create model Choice
    - Create model Question
    - Add field question to choice
node1:/django/mysite# python manage.py sqlmigrate polls 0001
BEGIN;
--
-- 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);
--
-- 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);
--
-- Add field question to choice
--
ALTER TABLE `polls_choice` ADD COLUMN `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`);
COMMIT;


现在,再次运行migrate以在你的数据库中创建模型所对应的表:

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Rendering model states... DONE
  Applying polls.0001_initial... OK


玩转API

现在,让我们进入Python的交互式shell,玩转这些Django提供给你的API。 使用如下命令来调用Python shell:


$ python manage.py shell

一旦你进入shell,请浏览database API:

>>> from polls.models import Question, Choice
>>> Question.objects.all()
<QuerySet []>

Django管理后台简介


创建一个管理员用户¶
首先,我们需要创建一个能够登录管理后台站点的用户。 运行如下命令:

$ python manage.py createsuperuser
原文地址:https://www.cnblogs.com/hzcya1995/p/13348302.html