Django学习记录之Django 1.8 教程(我只是官网的搬运工)Tutorial Part 1

9 篇文章 0 订阅
8 篇文章 0 订阅

Part 1
第一步:创建项目
(确保你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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值