mvc或者说是mtv模式,主要为了让数据模型、业务逻辑、表现逻辑尽量的分离,实现松散耦合。
这次学习是一个新的例子,在以前的mysite目录里面增加一个books的应用,进入mysite目录,执行:
python manage.py startapp books
创建了一个目录,books,里面有一些空文件:)
books/
__init__.py
models.py
tests.py
views.py
首先编辑models.py:
from django.db import models
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 __unicode__(self):
return self.name
class Meta:
ordering = ['name']
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
def __unicode__(self):
return u'%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 __unicode__(self):
return self.title
再编辑mysite下面的文件:settings.py:
找到INSTALLED_APPS 这里,更改为:
INSTALLED_APPS = (
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.sites',
'mysite.books',
)
在mysite目录下运行:python manage.py validate
0 errors found 就可以了。
下面要配置数据库了,在setting.py文件里面。找到对应的地方更改如下:
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'c:/mydata.db' # change it free
测试一下:运行:
python manage.py
shell
>>>from django.db import connection
>>>cursor = connection.cursor()
没有错误就ok了,否则根据错误提示调试一下
运行python manage.py syncdb
将模型同步到数据库中。
Creating table books_publisher
Creating table books_author
Creating table books_book
Installing index for books.Book model
生成的数据注意都是小写,引用的时候要注意啊。。。
常用语句说明:首先准备数据。
>>> from books.models import Publisher
插入数据
>>> p1 = Publisher.objects.create(name='Apress',
... address='2855 Telegraph Avenue',
... city='Berkeley', state_province='CA', country='U.S.A.',
... website='http://www.apress.com/')
>>> p1.save()
更新数据
>>> p1.name = 'Apress Publishing'
>>> p1.save()
>>> Publisher.objects.all().update(country='USA')
查找/选择数据
>>> Publisher.objects.filter(name='Apress')
>>> Publisher.objects.filter(country="U.S.A.", state_province="CA") # and 双条件
>>> from django.db.models import Q
>>> Publisher.objects.filter(Q(name='Apress') | Q(name='newone')) # or 条件
>>> Publisher.objects.filter(name__contains="press") # 模糊查找,相当于name like '%press%'
排序数据,类似的还有加下双划线icontains (不区分大小写的like),
startswith、endswith、range (SQL
BETWEEN语句等).
>>> Publisher.objects.order_by("name") # 到排序用-name
综合
>>> Publisher.objects.filter(country="U.S.A.").order_by("-name")
删除数据
>>> p = Publisher.objects.get(name="O'Reilly")
>>> p.delete()
>>> Publisher.objects.filter(country='USA').delete()
执行自定义SQL
在自定义 model 方法和模块级方法里,你可以自由的执行自定义SQL语句. 对象 django.db.connection 表示当前的数据库连接. 调用 connection.cursor() 得到一个游标对象. 然后调用 cursor.execute(sql, [params])``以执行 SQL 语句, 使用 ``cursor.fetchone() 或 cursor.fetchall() 得到结果集. 下面是一个例子:
from django.db import connection
cursor = connection.cursor()
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
如果你的SQL语句改变了数据库中的数据 -- 比如你使用了 DELETE 或 UPDATE 语句. 你需要调用 connection.commit() 来使你的修改生效. 例子:
from django.db import connection
cursor = connection.cursor()
cursor.execute("DELETE FROM bar WHERE baz = %s", [self.baz])
connection.commit()
connection 和 cursor 直接调用 Python DB-API. 如果你对 Python DB-API 不熟悉, 注意``cursor.execute()`` 中的SQL语句使用了占位符 "%s", 这比直接在 SQL语句中指定参数要灵活. 如果你使用此技术, 后台的数据库会自动的在需要时用引号引并转义你的参数.
最后提醒一下: 如果你想要的仅仅是一个自定义的 WHERE 子句,你可以在标准查询 API 中通过指定 where, tables 和 params 参数来完成同样的功能.参阅 其它查询选项.
在dos下运行:python manage.py sqlall books
会列出所有的sql语句。
注意:
CREATE TABLE "books_book_authors" (
"id" integer 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");
外键产生一个索引,对应publisher的id。book中publisher字段存的是一个id值。
将常用的业务逻辑写到特定的模型中也是一个比较不错的封装方法:
from django.db import models
class DahlBookManager(models.Manager):
def get_query_set(self):
return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
# ...
objects = models.Manager() # The default manager.
dahl_objects = DahlBookManager() # The Dahl-specific manager.