码迷,mamicode.com
首页 > 其他好文 > 详细

Django L1 编写你的第一个Django应用,第1部分

时间:2017-02-09 18:43:39      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:类型   理解   认证   _id   一个数据库   auto   打印   null   creat   

http://python.usyiyi.cn/django/index.html

 

1 查看django版本

python -c ‘import django ; print(django.get_version())‘
1.10.5

  

创建一个项目

$ django-admin startproject ltest

$tree
.
├── ltest
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── settings.py
│   ├── settings.pyc
│   ├── urls.py
│   └── wsgi.py
├── manage.py

  

settings.py 

默认情况下,INSTALLED_APPS包含下面的应用,它们都是Django 与生俱来的:

django.contrib.admin —— 管理站点。你将在本教程的第2部分使用到它。
django.contrib.auth —— 认证系统。
django.contrib.contenttypes —— 用于内容类型的框架。
django.contrib.sessions —— 会话框架。
django.contrib.messages —— 消息框架。
django.contrib.staticfiles —— 管理静态文件的框架。
这些应用,默认包含在Django中,以方便通用场合下使用。

然而上面的部分应用至少需要使用一个数据库表,因此我们需要在使用它们之前先在数据库中创建相应的表。要做到这一点,请运行以下命令:

  

开发服务器

$ python manage.py runserver
$ python manage.py runserver 0.0.0.0:8080

  

创建模型

一个项目可以有多个应用,一个应用可以属于多个项目

$ python manage.py startapp polls
$ tree
.
├── ltest
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── settings.py
│   ├── settings.pyc
│   ├── urls.py
│   └── wsgi.py
├── manage.py
├── tasks
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
└── templates

  

 

创建模型

cat tasks/models.py 
from __future__ import unicode_literals

from django.db import models

# Create your models here.

class Questions(models.Model):
    question_text = models.CharField(max_length=200)
    pub_data = models.DateTimeField(data published)


class Choice(models.Model):
    question = models.ForeignKey(Questions)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

 

激活模型

  Django 应用是可以“热插拔”的,即可以在多个项目中使用同一个应用,也可以分发这些应用, 因为它们不需要与某个特定的Django安装绑定。

$grep -Ri  INSTALLED_APPS -A 10 ./ltest/settings.py
INSTALLED_APPS = [
    ‘django.contrib.admin‘,
    ‘django.contrib.auth‘,
    ‘django.contrib.contenttypes‘,
    ‘django.contrib.sessions‘,
    ‘django.contrib.messages‘,
    ‘django.contrib.staticfiles‘,

    ‘tasks‘,
]

  

$python manage.py makemigrations tasks
Migrations for ‘tasks‘:
  tasks/migrations/0001_initial.py:
    - Create model Choice
    - Create model Questions
    - Add field question to choice

有一个命令可以运行这些迁移文件并自动管理你的数据库模式 —— 它叫做migrate,我们一会儿会用到它 —— 但是首先,让我们看一下迁移行为将会执行哪些SQL语句。sqlmigrate命令接收迁移文件的名字并返回它们的SQL语句:

t$ python manage.py sqlmigrate tasks 0001
BEGIN;
--
-- Create model Choice
--
CREATE TABLE "tasks_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
--
-- Create model Questions
--
CREATE TABLE "tasks_questions" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_data" datetime NOT NULL);
--
-- Add field question to choice
--
ALTER TABLE "tasks_choice" RENAME TO "tasks_choice__old";
CREATE TABLE "tasks_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "tasks_questions" ("id"));
INSERT INTO "tasks_choice" ("choice_text", "votes", "id", "question_id") SELECT "choice_text", "votes", "id", NULL FROM "tasks_choice__old";
DROP TABLE "tasks_choice__old";
CREATE INDEX "tasks_choice_7aa0f6ee" ON "tasks_choice" ("question_id");
COMMIT;

  

  • sqlmigrate命令并不会在你的数据库上真正运行迁移文件 —— 它只是把Django 认为需要的SQL打印在屏幕上以让你能够看到。 这对于检查Django将要进行的数据库操作或者你的数据库管理员需要这些SQL脚本是非常有用的。

 

$ python manage.py check #它会检查你的项目中的模型是否存在问题,而不用执行迁移或者接触数据库。
System check identified no issues (0 silenced).

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

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, tasks
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying sessions.0001_initial... OK
  Applying tasks.0001_initial... OK

  

迁移功能非常强大,可以让你在开发过程中不断修改你的模型而不用删除数据库或者表然后再重新生成一个新的 —— 它专注于升级你的数据库且不丢失数据。 我们将在本教程的后续章节对迁移进行深入地讲解,但是现在,请记住实现模型变更的三个步骤:

 

玩转API 

$ python manage.py shell
Python 2.7.6 (default, Oct 26 2016, 20:30:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>

 

如果你不想使用manage.py,也没问题。只要设置DJANGO_SETTINGS_MODULE 环境变量为 mysite.settings,启动一个普通的Python shell,然后建立Django:

>>> import django
>>> django.setup()
  

数据库API

 

 

给你的模型添加__str__()方法很重要,不仅会使你自己在使用交互式命令行时看得更加方便,而且会在Django自动生成的管理界面中使用对象的这种表示。

__str__ 还是 __unicode__?

对于Python 3来说,这很简单,只需使用__str__()

对于Python 2来说,你应该定义__unicode__()方法并返回unicode 值。Django 模型具有一个默认的__str__() 方法,它会调用__unicode__()并将结果转换为UTF-8 字节字符串。这意味着unicode(p)将返回一个Unicode 字符串,而str(p)将返回一个字节字符串,其字符以UTF-8编码。Python 的行为则相反:对象__unicode__方法调用 __str__方法并将结果理解为ASCII 字节字符串。这个不同点可能会产生困惑。

 

models.py

from __future__ import unicode_literals

from django.db import models

# Create your models here.

class Questions(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField(‘data published‘)

    def __unicode__(self):      #
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Questions)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __unicode__(self):      #
        return self.choice_text

  

 

 

Django L1 编写你的第一个Django应用,第1部分

标签:类型   理解   认证   _id   一个数据库   auto   打印   null   creat   

原文地址:http://www.cnblogs.com/zsr0401/p/6383248.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!