最近因为项目需要,开始研究django,下面分享我的使用过程,希望对大家有用
官网:
安装:
sudo apt-get install python-django
or
sudo pip install django
安装有效性检查
django-admin --version
创建项目
django-admin startproject mysite
目录结构
.
├── manage.py
└── mysite
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
启动服务
python manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
You have unapplied migrations; your app may not work properly until they are applied.
Run ‘python manage.py migrate‘ to apply them.
April 21, 2016 - 07:32:20
Django version 1.9.5, using settings ‘mysite.settings‘
Starting development server at http://127.0.0.1:8000/
目录结构
├── db.sqlite3
├── manage.py
└── mysite
├── __init__.py
├── __init__.pyc
├── settings.py
├── settings.pyc
├── urls.py
├── urls.pyc
├── wsgi.py
└── wsgi.pyc
可见只多了 db.sqlite3文件及一些pyc文件
这个数据库文件的名字是在mysite/settings.py指定的
DATABASES = {
‘default‘: {
‘ENGINE‘: ‘django.db.backends.sqlite3‘,
‘NAME‘: os.path.join(BASE_DIR, ‘db.sqlite3‘),
}
}
这里默认是sqlite3数据库引擎,有需要可以更改引擎比如mysql等等
我们来看下这个数据库生成了什么?
sqlite3 db.sqlite3
SQLite version 3.8.2 2013-12-06 14:53:30
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE "django_migrations" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "app" varchar(255) NOT NULL, "name" varchar(255) NOT NULL, "applied" datetime NOT NULL);
COMMIT;
sqlite>
可以看出只是创建了一个表:django_migrations
创建应用
python manage.py startapp local_db
我们来看看生成了哪些文件:
├── db.sqlite3
├── local_db
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── manage.py
└── mysite
├── __init__.py
├── __init__.pyc
├── settings.py
├── settings.pyc
├── urls.py
├── urls.pyc
├── wsgi.py
└── wsgi.pyc
可见生成了local_db目录
jivin@jivin-ThinkPad-T450:~/back/experiment/django/mysite/local_db$ cat admin.py
from django.contrib import admin
# Register your models here.
jivin@jivin-ThinkPad-T450:~/back/experiment/django/mysite/local_db$ cat apps.py
from __future__ import unicode_literals
from django.apps import AppConfig
class LocalDbConfig(AppConfig):
name = ‘local_db‘
jivin@jivin-ThinkPad-T450:~/back/experiment/django/mysite/local_db$ cat models.py
from __future__ import unicode_literals
from django.db import models
# Create your models here.
jivin@jivin-ThinkPad-T450:~/back/experiment/django/mysite/local_db$ cat views.py
from django.shortcuts import render
# Create your views here.
jivin@jivin-ThinkPad-T450:~/back/experiment/django/mysite/local_db$ cat tests.py
from django.test import TestCase
# Create your tests here.
写第一个view
修改local_db/views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You‘re at the local_db index.")
将url映射到这个函数
新增local_db/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r‘^$‘, views.index, name=‘index‘),
]
增加urls文件
cat mysite/urls.py
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include, url
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^local_db/‘, include(‘local_db.urls‘)),
]
重新执行server:python manage.py runserver
然后在浏览器输入:http://127.0.0.1:8000/local_db/
migrate
每次新增一个应用时,需要创建他们需要的数据库,这时就需要先执行这个
python manage.py migrate
Operations to perform:
Apply all migrations: admin, contenttypes, auth, sessions
Running migrations:
Rendering model states... DONE
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 sessions.0001_initial... OK
[email protected]-ThinkPad-T450:~/back/experiment/django/mysite$ sqlite3 db.sqlite3
SQLite version 3.8.2 2013-12-06 14:53:30
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE "django_migrations" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "app" varchar(255) NOT NULL, "name" varchar(255) NOT NULL, "applied" datetime NOT NULL);
INSERT INTO "django_migrations" VALUES(1,‘contenttypes‘,‘0001_initial‘,‘2016-04-21 08:01:35.838744‘);
INSERT INTO "django_migrations" VALUES(2,‘auth‘,‘0001_initial‘,‘2016-04-21 08:01:35.904882‘);
INSERT INTO "django_migrations" VALUES(3,‘admin‘,‘0001_initial‘,‘2016-04-21 08:01:35.952628‘);
INSERT INTO "django_migrations" VALUES(4,‘admin‘,‘0002_logentry_remove_auto_add‘,‘2016-04-21 08:01:36.006238‘);
INSERT INTO "django_migrations" VALUES(5,‘contenttypes‘,‘0002_remove_content_type_name‘,‘2016-04-21 08:01:36.087153‘);
INSERT INTO "django_migrations" VALUES(6,‘auth‘,‘0002_alter_permission_name_max_length‘,‘2016-04-21 08:01:36.149247‘);
INSERT INTO "django_migrations" VALUES(7,‘auth‘,‘0003_alter_user_email_max_length‘,‘2016-04-21 08:01:36.218252‘);
INSERT INTO "django_migrations" VALUES(8,‘auth‘,‘0004_alter_user_username_opts‘,‘2016-04-21 08:01:36.275377‘);
INSERT INTO "django_migrations" VALUES(9,‘auth‘,‘0005_alter_user_last_login_null‘,‘2016-04-21 08:01:36.334689‘);
INSERT INTO "django_migrations" VALUES(10,‘auth‘,‘0006_require_contenttypes_0002‘,‘2016-04-21 08:01:36.357559‘);
INSERT INTO "django_migrations" VALUES(11,‘auth‘,‘0007_alter_validators_add_error_messages‘,‘2016-04-21 08:01:36.414787‘);
INSERT INTO "django_migrations" VALUES(12,‘sessions‘,‘0001_initial‘,‘2016-04-21 08:01:36.459969‘);
CREATE TABLE "auth_group" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(80) NOT NULL UNIQUE);
CREATE TABLE "auth_group_permissions" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "group_id" integer NOT NULL REFERENCES "auth_group" ("id"), "permission_id" integer NOT NULL REFERENCES "auth_permission" ("id"));
CREATE TABLE "auth_user_groups" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "user_id" integer NOT NULL REFERENCES "auth_user" ("id"), "group_id" integer NOT NULL REFERENCES "auth_group" ("id"));
CREATE TABLE "auth_user_user_permissions" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "user_id" integer NOT NULL REFERENCES "auth_user" ("id"), "permission_id" integer NOT NULL REFERENCES "auth_permission" ("id"));
CREATE TABLE "django_admin_log" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "object_id" text NULL, "object_repr" varchar(200) NOT NULL, "action_flag" smallint unsigned NOT NULL, "change_message" text NOT NULL, "content_type_id" integer NULL REFERENCES "django_content_type" ("id"), "user_id" integer NOT NULL REFERENCES "auth_user" ("id"), "action_time" datetime NOT NULL);
CREATE TABLE "django_content_type" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "app_label" varchar(100) NOT NULL, "model" varchar(100) NOT NULL);
INSERT INTO "django_content_type" VALUES(1,‘admin‘,‘logentry‘);
INSERT INTO "django_content_type" VALUES(2,‘auth‘,‘permission‘);
INSERT INTO "django_content_type" VALUES(3,‘auth‘,‘group‘);
INSERT INTO "django_content_type" VALUES(4,‘auth‘,‘user‘);
INSERT INTO "django_content_type" VALUES(5,‘contenttypes‘,‘contenttype‘);
INSERT INTO "django_content_type" VALUES(6,‘sessions‘,‘session‘);
CREATE TABLE "auth_permission" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "content_type_id" integer NOT NULL REFERENCES "django_content_type" ("id"), "codename" varchar(100) NOT NULL, "name" varchar(255) NOT NULL);
INSERT INTO "auth_permission" VALUES(1,1,‘add_logentry‘,‘Can add log entry‘);
INSERT INTO "auth_permission" VALUES(2,1,‘change_logentry‘,‘Can change log entry‘);
INSERT INTO "auth_permission" VALUES(3,1,‘delete_logentry‘,‘Can delete log entry‘);
INSERT INTO "auth_permission" VALUES(4,2,‘add_permission‘,‘Can add permission‘);
INSERT INTO "auth_permission" VALUES(5,2,‘change_permission‘,‘Can change permission‘);
INSERT INTO "auth_permission" VALUES(6,2,‘delete_permission‘,‘Can delete permission‘);
INSERT INTO "auth_permission" VALUES(7,3,‘add_group‘,‘Can add group‘);
INSERT INTO "auth_permission" VALUES(8,3,‘change_group‘,‘Can change group‘);
INSERT INTO "auth_permission" VALUES(9,3,‘delete_group‘,‘Can delete group‘);
INSERT INTO "auth_permission" VALUES(10,4,‘add_user‘,‘Can add user‘);
INSERT INTO "auth_permission" VALUES(11,4,‘change_user‘,‘Can change user‘);
INSERT INTO "auth_permission" VALUES(12,4,‘delete_user‘,‘Can delete user‘);
INSERT INTO "auth_permission" VALUES(13,5,‘add_contenttype‘,‘Can add content type‘);
INSERT INTO "auth_permission" VALUES(14,5,‘change_contenttype‘,‘Can change content type‘);
INSERT INTO "auth_permission" VALUES(15,5,‘delete_contenttype‘,‘Can delete content type‘);
INSERT INTO "auth_permission" VALUES(16,6,‘add_session‘,‘Can add session‘);
INSERT INTO "auth_permission" VALUES(17,6,‘change_session‘,‘Can change session‘);
INSERT INTO "auth_permission" VALUES(18,6,‘delete_session‘,‘Can delete session‘);
CREATE TABLE "auth_user" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "password" varchar(128) NOT NULL, "last_login" datetime NULL, "is_superuser" bool NOT NULL, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL, "email" varchar(254) NOT NULL, "is_staff" bool NOT NULL, "is_active" bool NOT NULL, "date_joined" datetime NOT NULL, "username" varchar(30) NOT NULL UNIQUE);
CREATE TABLE "django_session" ("session_key" varchar(40) NOT NULL PRIMARY KEY, "session_data" text NOT NULL, "expire_date" datetime NOT NULL);
DELETE FROM sqlite_sequence;
INSERT INTO "sqlite_sequence" VALUES(‘django_migrations‘,12);
INSERT INTO "sqlite_sequence" VALUES(‘django_admin_log‘,0);
INSERT INTO "sqlite_sequence" VALUES(‘django_content_type‘,6);
INSERT INTO "sqlite_sequence" VALUES(‘auth_permission‘,18);
INSERT INTO "sqlite_sequence" VALUES(‘auth_user‘,0);
CREATE UNIQUE INDEX "auth_group_permissions_group_id_0cd325b0_uniq" ON "auth_group_permissions" ("group_id", "permission_id");
CREATE INDEX "auth_group_permissions_0e939a4f" ON "auth_group_permissions" ("group_id");
CREATE INDEX "auth_group_permissions_8373b171" ON "auth_group_permissions" ("permission_id");
CREATE UNIQUE INDEX "auth_user_groups_user_id_94350c0c_uniq" ON "auth_user_groups" ("user_id", "group_id");
CREATE INDEX "auth_user_groups_e8701ad4" ON "auth_user_groups" ("user_id");
CREATE INDEX "auth_user_groups_0e939a4f" ON "auth_user_groups" ("group_id");
CREATE UNIQUE INDEX "auth_user_user_permissions_user_id_14a6b632_uniq" ON "auth_user_user_permissions" ("user_id", "permission_id");
CREATE INDEX "auth_user_user_permissions_e8701ad4" ON "auth_user_user_permissions" ("user_id");
CREATE INDEX "auth_user_user_permissions_8373b171" ON "auth_user_user_permissions" ("permission_id");
CREATE INDEX "django_admin_log_417f1b1c" ON "django_admin_log" ("content_type_id");
CREATE INDEX "django_admin_log_e8701ad4" ON "django_admin_log" ("user_id");
CREATE UNIQUE INDEX "django_content_type_app_label_76bd3d3b_uniq" ON "django_content_type" ("app_label", "model");
CREATE UNIQUE INDEX "auth_permission_content_type_id_01ab375a_uniq" ON "auth_permission" ("content_type_id", "codename");
CREATE INDEX "auth_permission_417f1b1c" ON "auth_permission" ("content_type_id");
CREATE INDEX "django_session_de54fa62" ON "django_session" ("expire_date");
COMMIT;
新增模型
修改local_db/models.py
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)
修改mysite/settings.py让其生效:
INSTALLED_APPS = [
‘local_db.apps.LocalDbConfig‘,
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
]
生成model对应的migrate:
python manage.py makemigrations local_db
Migrations for ‘local_db‘:
0001_initial.py:
- Create model Choice
- Create model Question
- Add field question to choice
这条命令就是为了生成local_db/0001_initial.py
然后我们看对应sqlmigrate的动作
python manage.py sqlmigrate local_db 0001
这个0001对应前面local_db/migrations/0001_initial.py文件名前缀
BEGIN;
--
-- Create model Choice
--
CREATE TABLE "local_db_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL);
--
-- Create model Question
--
CREATE TABLE "local_db_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
--
-- Add field question to choice
--
ALTER TABLE "local_db_choice" RENAME TO "local_db_choice__old";
下面真正生成model对应的数据库表:
python manage.py migrate local_db
Operations to perform:
Apply all migrations: local_db
Running migrations:
Rendering model states... DONE
Applying local_db.0001_initial... OK
sqlite3 db.sqlite3
CREATE TABLE "local_db_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
CREATE TABLE "local_db_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "local_db_question" ("id"));
/**********************
* 本文来自博客 “爱踢门”
* 转载请标明出处:http://blog.csdn.net/itleaks
********************************/