Django学习记录之Django 1.8 教程(我只是官网的搬运工)Tutorial Part 1
2015-11-30 18:26
543 查看
Part 1
第一步:创建项目
(确保你path 包含django)
这将会创建一个项目在你的当前目录。该目录将会包含以一些文件
mysite/
manage.py
mysite/
init.py
settings.py
urls.py
wsgi.py
其中manage.py 将会是非常常用与命令行的一个py文件。
第二步:设置你的数据库
默认的django将会使用SQLite。
成功创建了数据库文件,试试运行下吧
你将会看到。。。
Performing system checks…
0 errors found
November 28, 2015 - 15:50:53
Django version 1.8, using settings ‘mysite.settings’
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
可以看到默认端口是8000,你可以通过
来更改。
第三步:创建app
现在你可以创建一个app项目了。请保证目前与manage.py位于同一目录下。
你将会创建如下文件在该目录下
polls/
init.py
admin.py
migrations/
init.py
models.py
tests.py
views.py
在这个简单的polls app 里面我们将创建两个models: Question and Choice。他们都有相应的工作。
现在更改polls/models.py 文件如下:
至此,你已经完成models的编写。接下来该是激活这个app了。
编辑 mysite/settings.py 改变 INSTALLED_APPS:
现在Django知道mysite已经有了polls这个app了。将他们关联一下:
你会看见:
Migrations for ‘polls’:
0001_initial.py:
- Create model Question
- Create model Choice
- Add field question to choice
tips: 通过运行 makemigrations 告诉Django 你对models做了一些改变。并且你想保存他们。
接下来,运行:
你将会看到:
BEGIN;
CREATE TABLE “polls_choice” (
“id” serial NOT NULL PRIMARY KEY,
“choice_text” varchar(200) NOT NULL,
“votes” integer NOT NULL
);
CREATE TABLE “polls_question” (
“id” serial NOT NULL PRIMARY KEY,
“question_text” varchar(200) NOT NULL,
“pub_date” timestamp with time zone NOT NULL
);
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;
可能不尽相同但都差不多。
tips:特别的是 sqlmigrate 不会真的对数据库进行更改。
现在,运行 migrate 去真正改变数据库。保存上面的table(表):
Operations to perform:
Synchronize unmigrated apps: staticfiles, messages
Apply all migrations: admin, contenttypes, polls, auth, sessions
Synchronizing apps without migrations:
Creating tables…
Running deferred SQL…
Installing custom SQL…
Running migrations:
Rendering model states… DONE
Applying … OK
总结:
更改数据库的3步:
(*) 对你的models进行改变。(something you like)
( * ) RUN python manage.py makemigrations 保存对models的改变。
( * ) RUN python manage.py migrate 将models 的改变读入数据库。
第四步:玩转API
运行:
导入数据库的API
可以看到显示的是 [],这实在太丑了并且毫无帮助。让我们改改吧:
编辑 polls/models.py
加入str()方法。
加入新函数:
polls/models.py
再进入shell:
第一步:创建项目
(确保你path 包含django)
$django-admin startproject mysite(mysite为你的项目名字)
这将会创建一个项目在你的当前目录。该目录将会包含以一些文件
mysite/
manage.py
mysite/
init.py
settings.py
urls.py
wsgi.py
其中manage.py 将会是非常常用与命令行的一个py文件。
第二步:设置你的数据库
默认的django将会使用SQLite。
$python manage.py migrate
成功创建了数据库文件,试试运行下吧
$python manage.py runserver
你将会看到。。。
Performing system checks…
0 errors found
November 28, 2015 - 15:50:53
Django version 1.8, using settings ‘mysite.settings’
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
可以看到默认端口是8000,你可以通过
$python manage.py runserver 8080
来更改。
第三步:创建app
现在你可以创建一个app项目了。请保证目前与manage.py位于同一目录下。
$python manage.py startapp polls(polls为app名)
你将会创建如下文件在该目录下
polls/
init.py
admin.py
migrations/
init.py
models.py
tests.py
views.py
在这个简单的polls app 里面我们将创建两个models: Question and Choice。他们都有相应的工作。
现在更改polls/models.py 文件如下:
from django.db import models class Question(models.Model): #问题字符型字段,最大长度为200 question_text = models.CharField(max_length=200) #问题发布时间字段。 pub_date = models.DateTimeField('date published') class Choice(models.Model): #定义一个关系通过使用ForeignKey,这将会告诉django每个选择关联单个问题。 question = models.ForeignKey(Question) #选择字符型字段,最大长度200. choice_text = models.CharField(max_length=200) #票数整型字段,初始化为0 votes = models.IntegerField(default=0)
至此,你已经完成models的编写。接下来该是激活这个app了。
编辑 mysite/settings.py 改变 INSTALLED_APPS:
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #更改在这 'polls', )
现在Django知道mysite已经有了polls这个app了。将他们关联一下:
$python manage.py makemigrations polls
你会看见:
Migrations for ‘polls’:
0001_initial.py:
- Create model Question
- Create model Choice
- Add field question to choice
tips: 通过运行 makemigrations 告诉Django 你对models做了一些改变。并且你想保存他们。
接下来,运行:
$python manage.py sqlmigrate polls 0001
你将会看到:
BEGIN;
CREATE TABLE “polls_choice” (
“id” serial NOT NULL PRIMARY KEY,
“choice_text” varchar(200) NOT NULL,
“votes” integer NOT NULL
);
CREATE TABLE “polls_question” (
“id” serial NOT NULL PRIMARY KEY,
“question_text” varchar(200) NOT NULL,
“pub_date” timestamp with time zone NOT NULL
);
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;
可能不尽相同但都差不多。
tips:特别的是 sqlmigrate 不会真的对数据库进行更改。
现在,运行 migrate 去真正改变数据库。保存上面的table(表):
$python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: staticfiles, messages
Apply all migrations: admin, contenttypes, polls, auth, sessions
Synchronizing apps without migrations:
Creating tables…
Running deferred SQL…
Installing custom SQL…
Running migrations:
Rendering model states… DONE
Applying … OK
总结:
更改数据库的3步:
(*) 对你的models进行改变。(something you like)
( * ) RUN python manage.py makemigrations 保存对models的改变。
( * ) RUN python manage.py migrate 将models 的改变读入数据库。
第四步:玩转API
运行:
$python manage.py shell
导入数据库的API
>>>from polls.models import Question,Choice >>>Question.objects.all() [] #你还未有任何的问题。 >>>from django.utils import timezone >>>q = Question(question_text="what's new?",pub_date=timezone.now()) #保存into数据库 >>>q.save() #现在它将会有一个id >>>q.id 1 #如你所想,q传入的参数被models.py 中Question类接收。让我们看看吧。 >>>q.question_text "what's new?" >>>q.pub_date datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=) #你可以直接对这些变量进行更改,但要记得保存into数据库哦。 >>>q.question_text = "What's up?" >>>q.save() #objects.all() 显示数据库中所有的questions。 >>>Question.objects.all() []
可以看到显示的是 [],这实在太丑了并且毫无帮助。让我们改改吧:
编辑 polls/models.py
from django.db import models class Question(models.Model): # ... def __str__(self): # __unicode__ on Python 2 return self.question_text class Choice(models.Model): # ... def __str__(self): # __unicode__ on Python 2 return self.choice_text
加入str()方法。
加入新函数:
polls/models.py
import datetime from django.db import models from django.utils import timezone class Question(models.Model): # ... def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
再进入shell:
>>> from polls.models import Question, Choice >>> Question.objects.all() [] >>> Question.objects.filter(id=1) [] #str 方法 >>> Question.objects.filter(question_text__startswith='What') [] >>>from django.utils import timezone >>>current_year = timezone.now().year >>>Question.objects.get(pub_date__year=current_year) #请求的id不存在将会引发一个错误 >>>Question.objects.get(id=2) Traceback (most recent call last): ... DoesNotExist: Question matching query does not exist. #使用 >>> Question.objects.get(pk=1) >>> q = Question.objects.get(pk=1) >>> q.was_published_recently() True >>> q = Question.objects.get(pk=1) >>> q.choice_set.all() [] #建立3个选择 >>> q.choice_set.create(choice_text='Not much', votes=0) >>> q.choice_set.create(choice_text='The sky', votes=0) >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0) >>> c.question >>> q.choice_set.all() [, , ] >>> q.choice_set.count() 3 >>> Choice.objects.filter(question__pub_date__year=current_year) >>> c = q.choice_set.filter(choice_text__startswith='Just hacking') #删除一个选择 >>> c.delete()
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法