---
title: "Django如何在数据库中创建表"
author: "MyEyeOfJava"
date: "2011-03-04T14:45:54Z"
tags: []
categories: ["编程语言"]
slug: "django"
draft: false
lastmod: "2011-03-04T15:36:37Z"
id: 940853
url: "https://myeyeofjava.iteye.com/blog/940853"
---

1.前提是你安装了Django框架在你的项目中运行Django ZIP文件中的python Setup.py install

2.前提是你已经安装了MySQLdb这个框架在你的项目中1.2.2（直接有EXE文件）

3.前提是你已经安装了PIL-1.1.7.win32-py2.6.exe图片数据库在你的项目中

4.以上准备好之后，创建的Django项目`django-admin.py startproject demo`

5.运行你的Django服务`python manage.py runserver，这步完成之后你应该能访问http://localhost:8080了`

6.urls.py内存储所有的访问路径,settings.py内存储你的数据库配置

7.以mySQLdb为例配置settings.py

   DATABASES = {  
    'default': {  
        'ENGINE': 'mysql', # Add 'postgresql\_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.  
        'NAME': 'my',                      # Or path to database file if using sqlite3.  
        'USER': 'root',                      # Not used with sqlite3.  
        'PASSWORD': '123456',                  # Not used with sqlite3.  
        'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.  
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.  
    }  
}

8.挂载你的Django应用，Django必须要有应用挂载，这类似于创建你的web项目，命令为：python manage.py startapp books（创建一个叫books的应用，这样会有一个books的文件夹出现）同时，文件夹内生成了\_\_init\_\_.py以及views.py以及models.py文件，models.py文件这里写你的数据库表的定义

9.models.py内

```
from django.db import models

class Publisher(models.Model):
    name = models.CharField(maxlength=30)
    address = models.CharField(maxlength=50)
    city = models.CharField(maxlength=60)
    state_province = models.CharField(maxlength=30)
    country = models.CharField(maxlength=50)
    website = models.URLField()

class Author(models.Model):
    salutation = models.CharField(maxlength=10)
    first_name = models.CharField(maxlength=30)
    last_name = models.CharField(maxlength=40)
    email = models.EmailField()
    headshot = models.ImageField(upload_to='/tmp')

class Book(models.Model):
    title = models.CharField(maxlength=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)
    publication_date = models.DateField()
```

10.cmd内验证你的数据表（此时只验证错误，数据库表没有创建成功，0errors）

```
python manage.py validate
```

11\.

```
python manage.py sqlall books
```

    这里运行这个命令可以生成对应的SQL创建表的语句，但是表仍然没有创建

12\.

```
python manage.py syncdb
此时表终于在数据库中创建出来了
```