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