使用Django開發(fā)數(shù)據(jù)庫應用的最大一個好處在于,使用Django的models可以方便的操縱數(shù)據(jù)庫。models就相當于一個溝通應用與數(shù)據(jù)庫的橋梁,Django會自動將與models相關(guān)的內(nèi)容轉(zhuǎn)化成SQL語句,更新到數(shù)據(jù)庫中。使用Django,開發(fā)人員只需要將全部精力放在編寫Python程序上即可。

下面,為film應用創(chuàng)建數(shù)據(jù)表:
1、打開film目錄下面的models.py文件
2、書寫film應用使用到的數(shù)據(jù)類
from django.db import models

# 演員
class Actor(models.Model):
    first_name 
= models.CharField(max_length=30)
    last_name 
= models.CharField(max_length=30)
    birthday 
= models.DateField()

# 發(fā)行商
class Publisher(models.Model):
    name 
= models.CharField(max_length=30)

# 影片
class Film(models.Model):
    title 
= models.CharField(max_length=100)
    actors 
= models.ManyToManyField(Actor)
    pub_date 
= models.DateField()
    publisher 
= models.ForeignKey(Publisher)
這里沒有提供主鍵,因為Django會為每個class都自動生成一個名為id的主鍵。整型,自增。
class下的每一項都應該是一個field對象,Django的完整域列表可參考:http://docs.djangoproject.com/en/dev/ref/models/fields/,Django的models相關(guān)信息可參考:http://docs.djangoproject.com/en/dev/topics/db/models/,這里,只是簡單的示例models的用法。
3、更新數(shù)據(jù)庫
D:\mycode\mysite>python manage.py syncdb
發(fā)現(xiàn)報錯
SyntaxError: Non-ASCII character '\xe6' in file D:\mycode\mysite\..\mysite\film\models.py on line 3, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
因為源碼models.py中用到了中文(雖然是注釋。。。),但沒有指明編碼。
在models.py中加上:
#coding=utf8
重新執(zhí)行syncdb命令,發(fā)現(xiàn)除了我們的film的表之外,還增加了好多額外的信息:
D:\mycode\mysite>python manage.py syncdb
Creating table auth_permission
Creating table auth_group
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table film_actor
Creating table film_publisher
Creating table film_film

You just installed Django
's auth system, which means you don't have any superuse
rs defined.
Would you like to create one now? (yes
/no):

這是因為這是第一次執(zhí)行syncdb命令,除了film之外,settings.py中的INSTALLED_APPS列表中有許多默認應用,第一次執(zhí)行數(shù)據(jù)庫同步時會生成它們,輸入yes,創(chuàng)建admin應用的賬號信息。admin是一個系統(tǒng)自動生成的有用的管理工具。包括了大部分常見的后臺管理功能,非常實用。

如果沒錯的話,數(shù)據(jù)表就建好了。可以到MySQL下驗證:

mysql> use film;
Database changed
mysql
> show tables;
+----------------------------+
| Tables_in_film             |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_message               |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_content_type        |
| django_session             |
| django_site                |
| film_actor                 |
| film_film                  |
| film_film_actors           |
| film_publisher             |
+----------------------------+
14 rows in set (0.00 sec)

mysql
>
可以看到,數(shù)據(jù)庫表創(chuàng)建成功!