django相关常用命令
文章目录
1. 创建项目
django-admin startproject mysite
执行完命令后,会生成以下文件
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
2. 服务启动
python manage.py runserver
# 可以指定ip和端口号
python manage.py runserver 8080
python manage.py runserver 0:8000
3. 创建应用
python manage.py startapp polls
这将会创建一个 polls 目录,它的目录结构大致如下:
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
4. 创建表(模型)
4.1 创建相关表
这个migrate
命令检查INSTALLED_APPS
设置,为其中的每个应用创建需要的数据表。 只会迁移INSTALLED_APPS
中的
python manage.py migrate
4.2 迁移表模型
迁移表模型,需要指定app名称
python manage.py makemigrations polls
通过运行 makemigrations
命令,Django 会检测你对模型文件的修改(在这种情况下,你已经取得了新的),并且把修改的部分储存为一次 迁移
。
注意
- makemigrations会在当前目录下生成一个migrations文件夹,该文件夹的内容就是数据库要执行的内容
python manage.py makemigrations
- migrate就是执行之前生成的migrations文件,这一步才是操作数据库的一步
python manage.py migrate
Django每次更新模型都需要执行以上两步,需要注意的是Django模型增加内容需要设定变量的初始值,否则会在第一步出现问题
4.3 生成表的sql
python manage.py sqlmigrate polls 0001
返回对应的sql
BEGIN;
--
-- Create model Choice
--
CREATE TABLE "polls_choice" (
"id" serial NOT NULL PRIMARY KEY,
"choice_text" varchar(200) NOT NULL,
"votes" integer NOT NULL
);
--
-- Create model Question
--
CREATE TABLE "polls_question" (
"id" serial NOT NULL PRIMARY KEY,
"question_text" varchar(200) NOT NULL,
"pub_date" timestamp with time zone NOT NULL
);
--
-- Add field question to choice
--
ALTER TABLE "polls_choice" ADD COLUMN "question_id" integer NOT NULL;
ALTER TABLE "polls_choice" ALTER COLUMN "question_id" DROP DEFAULT;
CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");
ALTER TABLE "polls_choice"
ADD CONSTRAINT "polls_choice_question_id_246c99a640fbbd72_fk_polls_question_id"
FOREIGN KEY ("question_id")
REFERENCES "polls_question" ("id")
DEFERRABLE INITIALLY DEFERRED;
COMMIT;
5. 交互式 Python 命令行
python manage.py shell
这个就可以对模型(表)进行访问了
>>> from polls.models import Choice, Question # Import the model classes we just wrote.
# No questions are in the system yet.
>>> Question.objects.all()
<QuerySet []>
# Create a new Question.
# Support for time zones is enabled in the default settings file, so
# Django expects a datetime with tzinfo for pub_date. Use timezone.now()
# instead of datetime.datetime.now() and it will do the right thing.
>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
# Save the object into the database. You have to call save() explicitly.
>>> q.save()
# Now it has an ID.
>>> q.id
1
# Access model field values via Python attributes.
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
# Change values by changing the attributes, then calling save().
>>> q.question_text = "What's up?"
>>> q.save()
# objects.all() displays all the questions in the database.
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>
6. Django管理页面
6.1 创建管理员账号
python manage.py createsuperuser