django 对各种数据库提供了很好的支持,包括:postgresql、mysql、sqlite、oracle。
django 为这些数据库提供了统一的调用api。 我们可以根据自己业务需求选择不同的数据库。
mysql 是 web 应用中最常用的数据库。本章节我们将以 mysql 作为实例进行介绍。你可以通过本站的 mysql 教程 了解更多mysql的基础知识。
如果你没安装 mysql 驱动,可以执行以下命令安装:
sudo pip install mysqlclient
我们在项目的 settings.py 文件中找到 databases 配置项,将其信息修改为:
databases = { 'default': { 'engine': 'django.db.backends.mysql', 'name': 'test', 'user': 'test', 'password': 'test123', 'host':'localhost', 'port':'3306', } }
这里添加了中文注释,所以你需要在 helloworld/settings.py 文件头部添加 # -*- coding: utf-8 -*-。
上面包含数据库名称和用户的信息,它们与 mysql 中对应数据库和用户的设置相同。django 根据这一设置,与 mysql 中相应的数据库和用户连接起来。
django规定,如果要使用模型,必须要创建一个app。我们使用以下命令创建一个 testmodel 的 app:
python manage.py startapp testmodel
目录结构如下:
helloworld |-- testmodel | |-- __init__.py | |-- admin.py | |-- models.py | |-- tests.py | `-- views.py
我们修改 testmodel/models.py文件,代码如下:
helloworld/testmodel/models.py: 文件代码:
# models.py from django.db import models class test(models.model): name = models.charfield(max_length=20)
以上的类名代表了数据库名称,且继承了models.model,类里面的字段代表数据表中的字段(name),数据类型则由charfield(相当于varchar)、datefield(相当于datetime), max_length 参数限定长度。
接下来在settings.py中找到installed_apps这一项,如下:
installed_apps = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'testmodel', # 添加此项 )
在命令行中运行:
注意:在django 1.9及未来的版本种使用migrate代替syscdb。
$ python manage.py migrate # 创建表结构
$ python manage.py makemigrations testmodel # 让 django 知道我们在我们的模型有一些变更
$ python manage.py migrate testmodel # 创建表结构
看到几行"creating table…"的字样,你的数据表就创建好了。
creating tables ... …… creating table testmodel_test #我们自定义的表 ……
表名组成结构为:app名_类名(如:testmodel_test)。
注意:尽管我们没有在models给表设置主键,但是django会自动添加一个id作为主键。
接下来我们在 helloworld 目录中添加 testdb.py 文件,并修改urls.py:
from django.conf.urls import * from helloworld.view import hello from helloworld.testdb import testdb urlpatterns = patterns("", ('^hello/$', hello), ('^testdb/$', testdb), )
添加数据需要先创建对象,然后再执行 save 函数,相当于sql中的insert:
# -*- coding: utf-8 -*- from django.http import httpresponse from testmodel.models import test # 数据库操作 def testdb(request): test1 = test(name='w3cschool.cn') test1.save() return httpresponse("<p>数据添加成功!</p>")
访问http://192.168.45.3:8000/testdb/ 就可以看到数据添加成功的提示。
django提供了多种方式来获取数据库的内容,如下代码所示:
helloworld/helloworld/testdb.py: 文件代码:
# -*- coding: utf-8 -*- from django.http import httpresponse from testmodel.models import test # 数据库操作 def testdb(request): # 初始化 response = "" response1 = "" # 通过objects这个模型管理器的all()获得所有数据行,相当于sql中的select * from list = test.objects.all() # filter相当于sql中的where,可设置条件过滤结果 response2 = test.objects.filter(id=1) # 获取单个对象 response3 = test.objects.get(id=1) # 限制返回的数据 相当于 sql 中的 offset 0 limit 2; test.objects.order_by('name')[0:2] #数据排序 test.objects.order_by("id") # 上面的方法可以连锁使用 test.objects.filter(name="w3cschool.cn").order_by("id") # 输出所有数据 for var in list: response1 += var.name + " " response = response1 return httpresponse("<p>" + response + "</p>")
修改数据可以使用 save() 或 update():
helloworld/helloworld/testdb.py: 文件代码:
# -*- coding: utf-8 -*- from django.http import httpresponse from testmodel.models import test # 数据库操作 def testdb(request): # 修改其中一个id=1的name字段,再save,相当于sql中的update test1 = test.objects.get(id=1) test1.name = 'w3cschoolw3cschool教程' test1.save() # 另外一种方式 #test.objects.filter(id=1).update(name='w3cschoolw3cschool教程') # 修改所有的列 # test.objects.all().update(name='w3cschoolw3cschool教程') return httpresponse("<p>修改成功</p>")
删除数据库中的对象只需调用该对象的delete()方法即可:
helloworld/helloworld/testdb.py: 文件代码:
# -*- coding: utf-8 -*- from django.http import httpresponse from testmodel.models import test # 数据库操作 def testdb(request): # 删除id=1的数据 test1 = test.objects.get(id=1) test1.delete() # 另外一种方式 # test.objects.filter(id=1).delete() # 删除所有数据 # test.objects.all().delete() return httpresponse("<p>删除成功</p>")