1、下載安裝MySQLdb類別庫
http://www.djangoproject.com/r/python-mysql/
2、修改settings.py 設定資料屬性
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'djangodb', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': 'root', 'PASSWORD': 'root', 'HOST': '127.0.0.1', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '3306', # Set to empty string for default. } }
修改後進入DOS進入專案目錄下執行python manage .py shell指令啟動互動介面輸入程式碼驗證資料庫設定是否成功。沒報錯則成功!
>>> from django.db import connection >>> cursor = connection.cursor()
3、創建一個Django app
一個專案中包含一個或多個這樣的app。 app可以理解為一塊功能集合。例如產品管理模組就包含增刪該查等功能,可以把產品管理叫做一個app。每個Django app都有獨立的models,views等,易移植和被復用。
DOS進入專案目錄執行python manage.py startapp products產生目錄檔案如下:
products/ __init__.py models.py tests.py views.py
4、編寫models
from django.db import models # Create your models here. class Company(models.Model): full_name = models.CharField(max_length=30) address = models.CharField(max_length=50) tel = models.CharField(max_length=15,blank=True) class Product(models.Model): product_name = models.CharField(max_length=30) price = models.FloatField() stock = models.IntegerField(max_length=5) company = models.ForeignKey(Company)
5、模型安裝(修改settings.py)檢查和邏輯是否正確。
沒有錯誤則執行 python manage.py syncdb建立資料表。現在你可以看到你的資料庫除了生成了products_company,products_product外還創建了其它好幾個表,這些是django管理後台所需表暫不管。
6、簡單的增刪改查
進入python manage.py shell
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', # Uncomment the next line to enable admin documentation: 'django.contrib.admindocs', 'DjangoMysqlSite.products', )