Django ORM基本配置
到目前为止,当我们的程序涉及到数据库相关操作时,我们一般都会这么搞:
- 创建数据库,设计表结构和字段
- 使用 MySQLdb 来连接数据库,并编写数据访问层代码
- 业务逻辑层去调用数据访问层执行数据库操作
django为使用一种新的方式,即:关系对象映射(Object Relational Mapping,简称ORM),django中遵循 Code Frist 的原则,即:根据代码中定义的类来自动生成数据库表;
1、修改project数据库配置(程序主目录下的settings.py文件)
默认连接数据库为本地文件sqlite3:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
更换为指定的mysql数据库:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mysite', #一定要存在的数据库名 'USER': 'xxxx', 'PASSWORD': 'xxx', 'HOST': '192.168.xx.xx', 'PORT': '3306' } }
2、创建定义数据库表结构文件(对应app目录下的models.py文件)
生成一个简单的数据库表:
from django.db import models # Create your models here. class UserInfo(models.Model): username = models.CharField(max_length=32) passwd = models.CharField(max_length=64)
把对应的app名称加入到settings.py文件配置里:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cmdb02', ]
3、生成数据库表
执行下面命令:
python manage.py makemigrations python manage.py migrate # 生成数据表
注意:Django默认用的MysqlDB模块连接数据库,但在python3.x里面还没有这个模块,所有需要把连接数据库的模块改成pymsyql,修改project目录下的init.py文件
import pymysql pymysql.install_as_MySQLdb()
执行生成数据库表命令,遇到的问题:
a. django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
解决: 找到 python_path\Lib\site-packages\django\db\backends\mysql路径下的base.py, 注释以下代码:
b. AttributeError: 'str' object has no attribute 'decode'
解决: 找到 python_path\Lib\site-packages\django\db\backends\mysql路径下的operations.py, 修改以下代码:
query = query.encode(errors='replace') 将decode修改为encode
c. pymysql.err.InternalError: (1049, "Unknown database 'mysite'")
解决: 数据库创建数据库 mysite
4. Django数据库单表操作
1. 增加:
第一种写法:
def ormadd(request): UserInfo.objects.create(username='root',passwd='123456') return HttpResponse('orm add')
第二种写法:
def ormadd(request): dicts = {'username': "xiaoxiao", 'passwd': '666666'} UserInfo.objects.create(**dicts) return HttpResponse('orm add')
第三种写法:
def ormadd(request): userinfo = UserInfo(username='sb2',passwd='123456') userinfo.save() return HttpResponse('orm add')
2.删除数据
def ormdel(request): UserInfo.objects.filter(id=19).delete() return HttpResponse('orm dele')
3.更新数据
第一种写法:
def ormadd(request): UserInfo.objects.filter(id__gt=10).update(username='white') #id大于10的数据,更新name为101 return HttpResponse('orm update')
第二种写法:
def ormadd(request): dicts ={'username': 'black'} UserInfo.objects.filter(id__gt=10).update(**dicts) return HttpResponse('orm update')
4.查询数据
- 查询所有的数据
-
def ormadd(request): res = UserInfo.objects.all() #QuerySet类型,列表里每个元素都是obj对象 print(res) # <QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>]> for row in res: # 1 root 123456 # 2 admin 123123 print(row.id, row.username, row.passwd) return HttpResponse('orm select')
2.查询指定字段
-
def ormadd(request): res = UserInfo.objects.filter(username='root') #过滤后,结果为list #res = UserInfo.objects.filter(id=3) #根据id查询 new_res = {} if res: for row in res: new_res['id'] = row.id new_res['username'] = row.username new_res['passwd'] = row.passwd return render(request, 'login.html', {'new_res':new_res})
tmplate页面数据显示:
3. 获取查询第一条数据 和 统计匹配个数
-
def ormadd(request): #获取匹配的第一条数据 obj = UserInfo.objects.filter(username='root').first() #获取匹配的字段个数 c = UserInfo.objects.filter(username='root').count() return render(request, 'login.html', {'obj': obj, 'c': c})
template页面数据显示:
4. 比较值查询及多条件查询
def ormadd(request): UserInfo.objects.filter(id=3, username='root') #id=1 且 name=root UserInfo.objects.filter(id__gt=1, username='root') #id>1 且 name=root UserInfo.objects.filter(id__lt=1) #id<1 UserInfo.objects.filter(id__gte=1) #id>=1 UserInfo.objects.filter(id__lte=1) #id<=1