Django 基础知识汇总

使用

安装

pip install django

创建新项目

django-admin.py startproject my_project

创建新的App

# 在Django项目(my_project)的根目录下执行
python manage.py startapp my_app

启动服务

# make new migrations
python manage.py makemigrations
 
# apply all migrations
python manage.py migrate
 
# run server
python manage.py runserver 80

显示 SQL

$ python manage.py sqlmigrate my_app 0001
BEGIN;
--
-- Create model Status
--
CREATE TABLE "moments_status" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "text" varchar(140) NOT NULL, "pics" varchar(400) NULL, "pub_time" datetime NOT NULL);
--
-- Create model WeChatUser
--
CREATE TABLE "moments_wechatuser" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "motto" varchar(500) NULL, "pic" varchar(200) NULL, "region" varchar(50) NULL, "user_id" integer NOT NULL UNIQUE REFERENCES "auth_user" ("id"));
--
-- Add field user to status
--
ALTER TABLE "moments_status" RENAME TO "moments_status__old";
CREATE TABLE "moments_status" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "text" varchar(140) NOT NULL, "pics" varchar(400) NULL, "pub_time" datetime NOT NULL, "user_id" integer NOT NULL REFERENCES "moments_wechatuser" ("id"));
INSERT INTO "moments_status" ("text", "pub_time", "user_id", "id", "pics") SELECT "text", "pub_time", NULL, "id", "pics" FROM "moments_status__old";
DROP TABLE "moments_status__old";
CREATE INDEX "moments_status_user_id_d38910b1" ON "moments_status" ("user_id");
COMMIT;

创建用户

python manage.py createsuperuser

http://127.0.0.1:8888/admin

进入 shell 调试

python manage.py shell
from moments.models import Status
statuses = Status.objects.all()
print statuses.query
print statuses
statuses[0].user

数据库

测试环境,没有mysql时,可以将 mysql 切换为 sqlite3

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',  # 默认用mysql
        ...
    }
}

celery

启动 celery

python manage.py shell
python  manage.py  celery  worker  --settings=settings -l info
python  manage.py  celerybeat --settings=settings
from home_application import celery_tasks
celery_tasks.async_task(5, 8)        # 实时输出
celery_tasks.async_task.dely(5, 8)   # 延时执行
celery_tasks.async_task.apply_async(args=(5, 8))
import datatime
celery_tasks.async_task.apply_async(args=(5, 8), eta=datatime.datatime.now() + datatime.timedeta(seconds=60)) # 指定时间执行

celery 添加 tast 后,需要在 conf/default.py 中,添加 CELERY_IMPORTS

完毕。