Writing your first Django app, part 1--学习笔记

一:建立一个项目

   django-admin startproject poll_mysite

二: 配置项目

1.配置数据库

创建数据库
mysql> create database poll_mysite;
Query OK, 1 row affected (0.02 sec)

vim poll_mysite/settings.py,改使用mysql数据库
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'poll_mysite',
        'USER': 'root',
        'PASSWORD': 'budong',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

更改时区
TIME_ZONE = 'Asia/Shanghai'
USE_TZ = False

2.创建INSTALLED_APPS 中包含的APP使用的表

budong@budongdeMacBook-Pro:~/Downloads/code_test/poll_mysite$ python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: admin, contenttypes, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying sessions.0001_initial... OK

3.启动开发服务器

budong@budongdeMacBook-Pro:~/Downloads/code_test/poll_mysite$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
November 14, 2015 - 07:36:42
Django version 1.8.6, using settings 'poll_mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

4.访问http://127.0.0.1:8000/,看django是否正常工作

三:开始写polls应用

1.建立polls app

budong@budongdeMacBook-Pro:~/Downloads/code_test/poll_mysite$ python manage.py startapp polls
budong@budongdeMacBook-Pro:~/Downloads/code_test/poll_mysite$ tree polls
polls
├── __init__.py
├── admin.py
├── migrations
│   └── __init__.py
├── models.py
├── tests.py
└── views.py

1 directory, 6 files

2.建立polls models(数据模型)

budong@budongdeMacBook-Pro:~/Downloads/code_test/poll_mysite$ cat polls/models.py
from django.db import models

# Create your models here.

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)

3.激活 polls app

vim poll_mysite/settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls',
)

4.生成polls models(数据模型)对应的表

对你的models做了些改变时执行,将改变的地方保存到一个文件
budong@budongdeMacBook-Pro:~/Downloads/code_test/poll_mysite$ python manage.py makemigrations polls
Migrations for 'polls':
  0001_initial.py:
    - Create model Choice
    - Create model Question
    - Add field question to choice

看下执行migration时,都执行了那些sql语句
budong@budongdeMacBook-Pro:~/Downloads/code_test/poll_mysite$ python manage.py sqlmigrate polls 0001
BEGIN;
CREATE TABLE `polls_choice` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `choice_text` varchar(200) NOT NULL, `votes` integer NOT NULL);
CREATE TABLE `polls_question` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `question_text` varchar(200) NOT NULL, `pub_date` datetime(6) 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`);

COMMIT;

检查你的项目是否有问题
budong@budongdeMacBook-Pro:~/Downloads/code_test/poll_mysite$ python manage.py check
System check identified no issues (0 silenced).

生成polls models对应的表结构
budong@budongdeMacBook-Pro:~/Downloads/code_test/poll_mysite$ 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 polls.0001_initial... OK

四:使用API访问数据库

玩下数据层的API
budong@budongdeMacBook-Pro:~/Downloads/code_test/poll_mysite$ python manage.py shell
Python 2.7.10 (default, Aug 22 2015, 20:33:39)
Type "copyright", "credits" or "license" for more information.

IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]:

In [1]: from polls.models import Question,Choice

In [2]: Question.objects.all()
Out[2]: []

In [3]: from django.utils import timezone

In [4]: q = Question(question_text="What's new?",pub_date=timezone.now())

In [5]: q.save()

In [6]: q.id
Out[6]: 1L

In [7]: q.question_text
Out[7]: "What's new?"

In [8]: q.pub_date
Out[8]: datetime.datetime(2015, 11, 14, 8, 46, 52, 818143, tzinfo=<UTC>)

In [9]: q.question_text = "What's up?"

In [10]: q.save()

In [11]: Qustion.objects.all()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-11-01eb56d9d3a1> in <module>()
----> 1 Qustion.objects.all()

NameError: name 'Qustion' is not defined

In [12]: Question.objects.all()
Out[12]: [<Question: Question object>]

增加自定义方法
from django.db import models

import datetime
from django.utils import timezone

# Create your models here.

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

继续玩下API
budong@budongdeMacBook-Pro:~/Downloads/code_test/poll_mysite$ python manage.py shell
Python 2.7.10 (default, Aug 22 2015, 20:33:39)
Type "copyright", "credits" or "license" for more information.

IPython 1.2.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: from polls.models import Question,Choice

In [2]: Question.objects.a
Question.objects.aggregate  Question.objects.all        Question.objects.annotate

In [2]: Question.objects.all()
Out[2]: [<Question: What's up?>]

In [3]: Question.objects.filter(id=1)
Out[3]: [<Question: What's up?>]

In [4]: Question.objects.filter(question_text__startwith='What')

In [5]: Question.objects.filter(question_text__startswith='What')
Out[5]: [<Question: What's up?>]

In [6]: from django.utils import timezone

In [7]: current_year = timezone.now().year

In [8]: current_year
Out[8]: 2015

In [9]: Question.objects.filter(pub_date__year=current_year)
Out[9]: [<Question: What's up?>]

In [10]: Question.objects.get(pk=1)
Out[10]: <Question: What's up?>

In [11]: q = Question.objects.get(pk=1)

In [12]: q.was_published_recently()
Out[12]: True

In [13]: q.choice_set.all()
Out[13]: []

In [14]: q.choice_set.create(choice_text='Not much',votes=0)
Out[14]: <Choice: Not much>

In [15]: q.choice_set.create(choice_text='The sky',votes=0)
Out[15]: <Choice: The sky>

In [16]: c = q.choice_set.create(choice_text='Just hacking again',votes=0)

In [17]: c.questio
c.question     c.question_id

In [17]: c.question
Out[17]: <Question: What's up?>

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

In [19]: q.choice_set.count()
Out[19]: 3

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

In [22]: c = q.choice_set.filter(choice_text__startswith='Just hacking')

In [23]: c
Out[23]: [<Choice: Just hacking again>]

In [24]: c.delete()

In [25]: c
Out[25]: []

In [26]: q.choice_set.all()
Out[26]: [<Choice: Not much>, <Choice: The sky>]

参考资料:

Writing your first Django app, part 1: https://docs.djangoproject.com/en/1.8/intro/tutorial01/