Django Web 开发实战

编写数据模型:Models

South 安装及简单使用

安装South

$ pip install south

setttings.py 修改

将south加入到 INSTALLED_APP中。

同步数据库

$ ./manage.py syncdb
Syncing...
Creating tables ...
Creating table south_migrationhistory
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

Synced:
 > django.contrib.admin
 > django.contrib.auth
 > django.contrib.contenttypes
 > django.contrib.sessions
 > django.contrib.messages
 > django.contrib.staticfiles
 > south

Not synced (use migrations):
 -
(use ./manage.py migrate to migrate these)

你可以看到,新创建了一个south_migrationhistory数据表,这个表用于记录South操作的。

编写数据模型:Post

这步我们开始编写一个Post模型,即一篇单个博客需要的元素:

  • 标题
  • 内容
  • 作者
  • 发布日期

打开blog/models.py文件,我们这样编写:

# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(u"标题", max_length=128)
    author = models.ForeignKey(User)
    content = models.TextField(u"内容")
    pub_data = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-id"]

    def __unicode__(self):
        return self.title

    @models.permalink
    def get_absolute_url(self):
        return ('post', (), {'pk': self.pk})

然后你可以回到终端,查看一下生成的SQL代码:

$ ./manage.py sql blog
BEGIN;
CREATE TABLE "blog_post" (
    "id" integer NOT NULL PRIMARY KEY,
    "title" varchar(128) NOT NULL,
    "author_id" integer NOT NULL REFERENCES "auth_user" ("id"),
    "content" text NOT NULL,
    "pub_data" datetime NOT NULL
)
;

COMMIT;

通过编写模型,再使用Django的管理工具命令,就可以生成相应的数据库了。但在我们实际开发的时候,有时需会对模型字段进行添加,修改,或是删除,你再使用manage.py syncdb,数据库并不会发生什么变化,因此我们需要一个可以进行这方面操作的工具,这个工具就是Django中很实用的South管理工具了。

对于你创建的每一个Django App,你都需要先使用South初始化一次,当然只需要一次就行了:

$ ./manage.py schemamigration blog --initial
Creating migrations directory at '/Users/wyatt/git/djwebapp/djwebapp-blog/djwebapp-blog/djblog/blog/migrations'...
Creating __init__.py in '/Users/wyatt/git/djwebapp/djwebapp-blog/djwebapp-blog/djblog/blog/migrations'...
 + Added model blog.Post
Created 0001_initial.py. You can now apply this migration with: ./manage.py migrate blog

初始化之后,会在相应的App目录中生成一个新的文件夹,目录结构是这样的:

$ tree blog/
blog/
├── __init__.py
├── __init__.pyc
├── admin.py
├── migrations
│   ├── 0001_initial.py
│   ├── __init__.py
│   └── __init__.pyc
├── models.py
├── models.pyc
├── tests.py
├── views.py
└── views.pyc

1 directory, 11 files

这时,数据库还没有生成的,你需要使用South生成这个应用的数据库字段:

$ ./manage.py migrate blog
Running migrations for blog:
 - Migrating forwards to 0001_initial.
 > blog:0001_initial
 - Loading initial data for blog.
Installed 0 object(s) from 0 fixture(s)

这样,Django就会生成我们指定的模型的数据库表了。下面我们来创建一条记录。这里我们在终端下使用manage.py shell来演示一下:

$ ./manage.py shell
...
In [1]: from django.contrib.auth.models import User

In [2]: from blog.models import Post

In [3]: user = User.objects.get(pk=1)

In [5]: user.username
Out[5]: u'wyatt'

In [6]: p1 = Post(title='hello, djblog', author=user, content='hello, world')

In [7]: p1.save()

In [8]: p1.title
Out[8]: 'hello, djblog'

In [9]: p1.content
Out[9]: 'hello, world'

In [10]: p1.author
Out[10]: <User: wyatt>

In [11]: p1.author.username
Out[11]: u'wyatt'

./manage.py shell会调用你的Python Shell,如果你在所在的虚拟环境中安装了ipython,刚会调用ipython作为Shell,使用这个命令和直接使用ipython是不一样的,通过manage.py调用的shell会为你设置好Django环境变量。

这是一个非常棒的功能,在你过行数据库查询方面调试的时候,会非常方便。

当我们每做了一个较大改动的时候,你就可以把代码commit一次:

$ git add .
$ git commit -m 'add blog'
$ git push