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>]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值