Django笔记4

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/iteye_21297/article/details/81728419
[b]1.设置settings.py[/b]

DATABASE_ENGINE = 'mysql'
DATABASE_NAME = 'django'
DATABASE_USER = 'root'
DATABASE_PASSWORD = '123456'
DATABASE_HOST = 'localhost'
DATABASE_PORT = ''

要注意的是无论选择使用哪个数据库服务器,都必须下载和安装对应的数据库适配器。
Mysql为:http://www.djangoproject.com/r/python-mysql/
输入完设置后,测试一下配置情况。首先,转到mysite 项目目录,运行 python manage.py shell 命令。输入下面这些命令来测试你的数据库配置:
>>> from django.db import connection
>>> cursor = connection.cursor()
如果没有显示什么错误信息,那么你的数据库配置是正确的。

[b]2. 执行下面的命令来创建一个新app叫做books:[/b]
python manage.py startapp books

[b]3.添加模型,打开 models.py 并输入下面的内容[/b]

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()

[b]4.模型安装[/b]
再次编辑 settings.py 文件, 找到 INSTALLED_APPS 设置。

INSTALLED_APPS = (
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.sites',
'mysite.books'
)

现在我们可以创建数据库表了。首先,用下面的命令对校验模型的有效性:
python manage.py validate
按提示信息安装相应模块
books.author: “headshot”: To use ImageFields, you need to install the Python Ima
ging Library. Get it at http://www.pythonware.com/products/pil/ .
模型确认没问题了,运行下面的命令来生成 CREATE TABLE 语句:
python manage.py sqlall books
运行命令的结果是这样的:

BEGIN;
CREATE TABLE "books_publisher" (
"id" serial NOT NULL PRIMARY KEY,
"name" varchar(30) NOT NULL,
"address" varchar(50) NOT NULL,
"city" varchar(60) NOT NULL,
"state_province" varchar(30) NOT NULL,
"country" varchar(50) NOT NULL,
"website" varchar(200) NOT NULL
);
CREATE TABLE "books_book" (
"id" serial NOT NULL PRIMARY KEY,
"title" varchar(100) NOT NULL,
"publisher_id" integer NOT NULL REFERENCES "books_publisher" ("id"),
"publication_date" date NOT NULL
);
CREATE TABLE "books_author" (
"id" serial NOT NULL PRIMARY KEY,
"salutation" varchar(10) NOT NULL,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(40) NOT NULL,
"email" varchar(75) NOT NULL,
"headshot" varchar(100) NOT NULL
);
CREATE TABLE "books_book_authors" (
"id" serial NOT NULL PRIMARY KEY,
"book_id" integer NOT NULL REFERENCES "books_book" ("id"),
"author_id" integer NOT NULL REFERENCES "books_author" ("id"),
UNIQUE ("book_id", "author_id")
);
CREATE INDEX books_book_publisher_id ON "books_book" ("publisher_id");
COMMIT;

sqlall 命令并没有在数据库中真正创建数据表,只是把SQL语句段打印出来。你可以把这些语句段拷贝到你的SQL客户端去执行它。当然,Django提供了更简单的方法来执行这些SQL语句。运行 syncdb 命令:
python manage.py syncdb
你将会看到这样的内容:
Creating table books_publisher
Creating table books_book
Creating table books_author
Installing index for books.Book model

syncdb 命令是同步你的模型到数据库的一个简单方法。它会根据 INSTALLED_APPS 里设置的app来检查数据库,如果表不存在,它就会创建它。需要注意的是, syncdb 并 不能同步模型的修改到数据库。如果你修改了模型,然后你想更新数据库, syncdb 是帮不了你的。(稍后我们再讲这些。)
如果你再次运行 python manage.py syncdb ,什么也没发生,因为你没有添加新的模型或者添加新的app。所以,运行 python manage.py syncdb 总是安全的,它不会把事情搞砸。
如果你有兴趣,花点时间用你的SQL客户端登录进数据库服务器看看刚才Django创建的数据表。 Django带有一个命令行工具, python manage.py dbshell 。

[b]5.基本数据访问[/b]
运行 python manage.py shell 并输入下面的内容试试看:

>>> from books.models import Publisher
>>> p1 = Publisher(name='Addison-Wesley', address='75 Arlington Street',
... city='Boston', state_province='MA', country='U.S.A.',
... website='http://www.apress.com/')
>>> p1.save()
>>> p2 = Publisher(name="O'Reilly", address='10 Fawcett St.',
... city='Cambridge', state_province='MA', country='U.S.A.',
... website='http://www.oreilly.com/')
>>> p2.save()
>>> publisher_list = Publisher.objects.all()
>>> publisher_list
[<publisher : Publisher object>, </publisher><publisher : Publisher object>]
</publisher>

[b]6.添加模块的字符串表现[/b]
添加一个方法 __str__() 到 Publisher 对象。 __str__() 方法告诉Python要怎样把对象当作字符串来使用。请看下面:

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()
def __str__(self):
return self.name

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')
def __str__(self):
return '%s %s' % (self.first_name, self.last_name)

class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
def __str__(self):
return self.title

请确保你的每一个模型里都包含 __str__() 方法,这不只是为了交互时方便,也是因为 Django会在其他一些地方用 __str__() 来显示对象。
7.详细数据库操作参照http://djangobook.py3k.cn/chapter05/
展开阅读全文

没有更多推荐了,返回首页