文档下载地址:Django_2.0_中文教程 http://download.csdn.net/detail/julius_lee/6620099
在线地址:http://djangobook.py3k.cn/2.0/
Django 2.0 Book 关键内容记录,主要是为了帮助记忆和理清整个框架,同时以后忘了可以查看,回想。
旧方法弊端:创建数据库连接、创建数据库游标、执行某个语句、然后关闭数据库。反复重复同样的代码。
示例:
from django.shortcuts import render_to_response import MySQLdb def book_list(request): db = MySQLdb.connect(user='me', db='mydb', passwd='secret',host='localhost') cursor = db.cursor() cursor.execute('SELECT name FROM books ORDER BY name') names = [row[0] for row in cursor.fetchall()] db.close() return render_to_response('book_list.html', {'names': names})
结合之前的MVC(model-view-control)模式将数据存取逻辑、业务逻辑和表现逻辑组合在一起的软件架构,MTV开发模式则为:model-template-view,即数据存取层-表现层-业务逻辑层。
配置mysite/settings.py文件
# Database #https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }这一部分和教程上有些不一致,教程上比较旧,还需要手动配置。目前实际使用中是直接已经配置好,无需过多修改。
检测方法:
运行python manage.py shell
输入:
from django.db import connection cursor = connection.cursor ()查看是否有报错
Project与app区别:
Project:包含多个django app 多个以及相关配置
App:一套django功能的集合,通常包含模型和视图
1) 在mysite目录下创建books app
Python manage.py startapp books
创建目录如下:
books/
__init__.py
models.py
tests.py
views.py
对数据层来说它等同于CREATE TABLE 语句,只不过执行的是Python代码而不是 SQL,而且还包含了比数据库字段定义更多的含义。 Django用模型在后台执行SQL代码并把结果用Python的数据结构来描述。
1) 第一个模型:在books下编辑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() class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField() class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher) publication_date = models.DateField()
每个模型相当于单个数据表,每个属性是表中的一个字段,属性名就是字段名,类型相当于数据库的字段类型,即charField相当于varchar
对应的数据库描述实际是这样的:
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 );
实际是python类与数据库表建立对应的映射关系
2) 模型安装
1.即在数据库中创建数据库表
在settings.py文件中添加app- books
# Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'books', )
1. 验证模型有效性
Python manage.py validate
检查逻辑和语法
2. 生成TABLE
Python manage.py sqlall books
3. 提交SQL语句到数据库
Python manage.py syncdb
3) 数据访问
模型创建后,django就会为该模型提供python API
示例:
>>> from books.models import Publisher >>> p1 = Publisher(name='Apress',address='2855 Telegraph Avenue', ... city='Berkeley', state_province='CA', 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 object>]导入publisher模型类,创建publisher类的实例,调用save()保存对象至数据库
4)添加模块的字符串表现
对各个如publisher的类添加__unicode__()方法,返回对一个对象处理后的字符串表示
这样对象列表显示就变了:
>>> from books.models importPublisher >>> publisher_list =Publisher.objects.all() >>> publisher_list [<Publisher: Apress>, <Publisher:O'Reilly>]#直接显示了出版社名字
5)插入和更新数据
示例:
>>> p = Publisher(name='Apress', ... address='2855 Telegraph Ave.', ... city='Berkeley', ... state_province='CA', ... country='U.S.A.', ... website='http://www.apress.com/') >>> p.save()
这样可以插入很多很多
6)选择对象
示例:
>>> Publisher.objects.all() [<Publisher: Apress>, <Publisher:O'Reilly>]
7)数据过滤–filter()
示例:
>>>Publisher.objects.filter(name='Apress') [<Publisher: Apress>]
或
你可以传递多个参数到 filter()来缩小选取范围:
>>>Publisher.objects.filter(country="U.S.A.",state_province="CA") [<Publisher: Apress>]
8)获取单个对象–get()
示例:
>>>Publisher.objects.get(name="Apress") <Publisher: Apress>
含异常处理的:
try: p= Publisher.objects.get(name='Apress') except Publisher.DoesNotExist: print "Apress isn't in the database yet." else: print "Apress is in the database."
9)数据排序–order_by
示例:
>>>Publisher.objects.order_by("name") [<Publisher: Apress>, <Publisher:O'Reilly>]
10)连锁查询–过滤加排序
示例:
>>> Publisher.objects.filter(country="U.S.A.").order_by("-name") [<Publisher: O'Reilly>,<Publisher: Apress>]
11)限制返回数据—按需索取
示例:
>>>Publisher.objects.order_by('name')[0] <Publisher: Apress>
12)更新多个对象
示例:
>>>Publisher.objects.filter(id=52).update(name='Apress Publishing') #id需要查询获得 或: >>>Publisher.objects.all().update(country='USA') #更新并返回更改的数目
13)删除对象
示例:
删除部分
>>>Publisher.objects.filter(country='USA').delete() 或 >>> p =Publisher.objects.get(name="O'Reilly") >>> p.delete() >>> Publisher.objects.all() [<Publisher: Apress Publishing>]
删除全部
>>>Publisher.objects.filter(country='USA').delete() >>>Publisher.objects.all().delete() >>> Publisher.objects.all() []