首页 > 技术文章 > Django学习笔记之一

fastmover 2015-01-27 22:01 原文

一、Windows下安装 Django

1、下载安装包解压后放到本地目录如C:\Django-1.7.2 官网地址:https://www.djangoproject.com/download/ 

2、打开命令行,输入 cd C:\Django-1.7.2 然后定位到当前目录

3、输入 python setup.py install 开始安装

4、配置各种环境变量,C:\Python34\;C:\Python34\Scripts;C:\Python34\Lib\site-packages\Django-1.7.2-py3.4.egg\django;

5、验证是否安装成功

D:\project\mysite>python
>>> import django >>> print(django.get_version())
1.7.2

安装成功!

二、通过官网的简单投票系统学习使用[https://docs.djangoproject.com/en/1.7/intro/tutorial01/]

1、创建一个项目,先在命令行cd 到想要创建项目所在的目录如D:\project\,然后输入如下命令

django-admin.py startproject mysite

此时已经自动创建了如下目录

mysite/
    manage.py
    mysite/
        __init__.py
        settings.py
        urls.py
        wsgi.py

2、使用已经自动安装了的SQLite

python manage.py migrate

3、启动服务器,通过如下网址可以访问网页

python manage.py runserver
Performing system checks...

0 errors found
January 27, 2015 - 15:50:53
Django version 1.7, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

4、在网站下创建一个名叫pools的APP投票应用 

python manage.py startapp polls
被创建的目录如下:
polls/ __init__.py admin.py migrations/ __init__.py models.py tests.py views.py
 

5、创建Models(MVC架构中的model,用于自动生成对应的数据库)

1)打开文件polls/models.py添加如下代码
from django.db import models


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)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

2)激活Models

打开配置文件mysite/settings.py,把我们刚创建的pools添加进去
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls',
)

2.1)在命令行执行

python manage.py makemigrations polls  #这是第一步,创建对Model的修改,可以打开polls/migrations/0001_initial.py文件查看代码格式
Migrations for 'polls':
  0001_initial.py:
    - Create model Question
    - Create model Choice
    - Add field question to choice

或者输入:python manage.py sqlmigrate polls 0001查看创建了些什么,结果如下:
BEGIN;
CREATE TABLE polls_question (
    "id" serial NOT NULL PRIMARY KEY,
    "question_text" varchar(200) NOT NULL,
    "pub_date" timestamp with time zone NOT NULL
);

CREATE TABLE polls_choice (
    "id" serial NOT NULL PRIMARY KEY,
    "question_id" integer NOT NULL,
    "choice_text" varchar(200) NOT NULL,
    "votes" integer NOT NULL
);

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;

2.2)在命令行执行

python manage.py migrate   #这是第二步,应用刚才创建的对Model的修改,sqlLite数据库里面会自动根据Model来修改数据库
Apply all migrations: admin, contenttypes, polls, auth, sessions
Running migrations:
  Applying <migration name>... OK

此时数据库已经创建完了,可以打开python测试一下
>>> 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())
>>> q.save()
>>> q.id
>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
>>> q.question_text = "What's up?"
>>> q.save()
>>> Question.objects.all()
[<Question: Question object>]

修改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
添加自定义函数
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)
再随便玩玩

>>> from polls.models import Question, Choice

# 确保 __str__() 可用.
>>> Question.objects.all()
[<Question: What's up?>]

# Django自带的数据查询 API
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
>>> Question.objects.filter(question_text__startswith='What')
[<Question: What's up?>]

>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>

>>> Question.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Question matching query does not exist.


>>> Question.objects.get(pk=1)
<Question: What's up?>

# 确保我们的自定义函数可用.
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True


>>> q = Question.objects.get(pk=1)

>>> q.choice_set.all()
[]


>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)

>>> c.question
<Question: What's up?>

>>> q.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> q.choice_set.count()
3

>>> Choice.objects.filter(question__pub_date__year=current_year)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]


>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()

 

 

 

 

 

推荐阅读