summerbell 发表于 2013-1-30 01:39:05

Django的数据库交互

首先为Django配置数据库
 
settings.py
 
 DATABASE_ENGINE = 'mysql'         # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.DATABASE_NAME = 'test'             # Or path to database file if using sqlite3.DATABASE_USER = 'root'             # Not used with sqlite3.DATABASE_PASSWORD = 'admin'         # Not used with sqlite3.DATABASE_HOST = '192.168.0.3'             # Set to empty string for localhost. Not used with sqlite3.DATABASE_PORT = '3306'             # Set to empty string for default. Not used with sqlite3. 

 
 
测试配置是否成功
运行python manage.py shell
 
>>> from django.db import connection
>>> cursor=connection.cursor()
>>> ^Z
 
Ok。现在创建一个新的app。
运行python manage.py startapp books
 
用Python定义模型。
 
models.py
 
 from django.db import models# Create your models here.class Publisher(models.Model):    name = models.CharField(max_length=30)    address = models.CharField(max_length=50)    city = models.CharField(max_length=60)    state_province = models.CharField(max_length=30)    country = models.CharField(max_length=50)    website = models.URLField()    class Author(models.Model):    salutation = models.CharField(max_length=10)    first_name = models.CharField(max_length=30)    last_name = models.CharField(max_length=40)    email = models.EmailField()    headshot = models.ImageField(upload_to='/tmp')    class Book(models.Model):    title = models.CharField(max_length=100)    authors = models.ManyToManyField(Author)    publisher = models.ForeignKey(Publisher)    publication_date = models.DateField() 

 
 
安装模型
 
settings.py
 
 INSTALLED_APPS = (    #'django.contrib.auth',    #'django.contrib.contenttypes',    #'django.contrib.sessions',    #'django.contrib.sites',    'testsite.books',) 

 
 
为模型生成CREATE TABLE语句
运行python manage.py sqlall books
 
将sql提交至数据库
运行python manage.py syncdb
 
运行python manage.py shell然后输入下面的代码试试:
>>> from books.models import Publisher
>>> p = Publisher(name='Apress', address='2560 Ninth St.',
... city='Berkeley', state_province='CA', country='U.S.A.',
... website='http://www.apress.com/')
>>> p.save()
>>> p = Publisher(name="O'Reilly", address='10 Fawcett St.',
... city='Cambridge', state_province='MA', country='U.S.A.',
... website='http://www.oreilly.com/')
>>> p.save()
>>> publisher_list = Publisher.objects.all()
>>> publisher_list
[<Publisher: Publisher object>, <Publisher: Publisher object>]
页: [1]
查看完整版本: Django的数据库交互