django基础(十一)之orm操作
django数据操作之创建表
##models.py
class UserInfo(models.Model): ##,以下会自动创建表,字段分别为用户名,字符串类型,指定长度 username = models.CharField(max_length=32) password = models.CharField(max_length=64) email = models.EmailField(max_length=64 null=True) ##null = True 表示可以为空 url = models.URLField(max_length=64 null=True) ##null = True 表示可以为空 ip = models.GenericIPAddressField(max_length=32) ###默认情况下会自动创建一列,id,并且为自增列,为主键 AutoField 为自增列,设置为自增后必须指定为主键,否则会报错,如下

models.py编辑好后,执行建表操作发现 提示no changs detected,如图

需要在settings.py 文件中添加要执行的项目名称(注册app应用),如下图所示,然后执行即可(或者直接执行migrate)
D:\django-project\test1>python manage.py makemigrations cmdb Migrations for 'cmdb': cmdb\migrations\0001_initial.py - Create model UserInfo D:\django-project\test1>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, cmdb, contenttypes, sessions Running migrations: Applying cmdb.0001_initial... OK

这样就创建了表,默认用的sqllite3(注意:创建完后的表名为 项目名称_表名,此示例为 cmdb_UserInfo)
如果要使用mysql数据库,则需要在settings.py里做如下设置:

将图中换成以下配置,但是mysql的数据库需要提前创建好
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'dbname', 'USER': 'root', 'PASSWORD': 'xxx', 'HOST': '', 'PORT': '', } }
注意:
由于Django内部连接MySQL时使用的是MySQLdb模块,而python3中还无此模块,所以需要使用pymysql来代替
如下设置放置的与project同名的配置的 __init__.py文件中
import pymysql pymysql.install_as_MySQLdb()
django orm 数据库增删改查
一、增
创建用户的三种方式
视图函数views.py
from cmdb import models def orm(request): ###创建用户① #models.UserInfo.objects.create(username="root",password="123456") ###创建用户②、 #dict = {"username":"test","password":"test"} #models.UserInfo.objects.create(**dict) ###创建用户③、 obj = models.UserInfo(username='testgao',password='testgao') obj.save() return HttpResponse('orm')

二、查
视图函数views.py
from cmdb import models
def orm(request):
result = models.UserInfo.objects.all() ###查询所有数据,UserInfo为表名 print (result) ##打印结果为一个对象 for row in result: ##遍历所有的数据 print (row.id,row.username,row.password) result1=models.UserInfo.objects.filter(username='root') ======> select * from userinfo where username='root' result2=models.UserInfo.objects.filter(username='root',password='123456') ======> select * from userinfo where username='root' and password='123456'
#and 和or操作
#result3=models.UserInfo.objects.filter(Q(id__gt=1)&Q(name="root")) “and” 操作
#result3=models.UserInfo.objects.filter((id__gt=1)|(name="root")) "or" 操作
#查询某一列(字段)数据 models.Application.objects.all().values_list('name') #Application为表名 print (result1.username) return HttpResponse('orm')

三、改
models.UserInfo.objects.all().update(password='aaa') ======> update userinfo set password='aaa' models.UserInfo.objects.filter(id='3').update(password='32432') ====> update userinfo set password='aaa' where id='3'
四、删
models.UserInfo.objects.all().delete() ======> delete from userinfo models.UserInfo.objects.filter('id=2').delete() =====> delete from userinfo where id = '2' models.UserInfo.objects.filter(username='root',password='123456').delete() ======> delete from userinfo where username='root' and password='123456'
orm查询实例
查询用户详细信息
访问url 127.0.0.1:8080/cmdb/login
urls.py

views.py

登录成功跳转到 index.html

index.html
<head> <meta charset="UTF-8"> <title>Title</title> <style> .menu{ display: block; padding:5px; } </style> </head> <body style="margin: 0;"> <div style="height:48px;background-color: black;color: red;border: 0" ></div> <div> <div style="position: absolute;top:48px;left: 0;bottom: 0;width: 200px;background-color: red"> <a class="menu" href="/cmdb/userinfo">用户管理</a> <a class="menu" href="/cmdb/usergroup_info">用户组管理</a> </div> </div> <div> <div style="position: absolute;top:48px;right: 0;bottom: 0;overflow: auto;background-color: darkgreen"></div> </div> </body>
主页

点击用户管理

跳转到 /cmdb/userinfo,进入urls.py 查看

视图函数views.py查看userinfo函数

查询所有的用户 跳转到userinfo.html
<head> <meta charset="UTF-8"> <title>Title</title> <style> .menu{ display: block; padding:5px; } </style> </head> <body style="margin: 0;"> <div style="height:48px;background-color: black;color: red;"> </div> <div> <!--左边菜单--> <div style="position: absolute;top:48px;left: 0;bottom: 0;width: 200px;background-color: red"> <a class="menu" href="/cmdb/userinfo">用户管理</a> <a class="menu" href="/cmdb/usergroup_info">用户组管理</a> </div> </div> <div> <!--右边菜单--> <div style="position: absolute;top:48px;left:210px;right: 0;bottom: 0;overflow: auto;"> <h1>用户列表</h1> <ul> {% for row in userlist %} <li><a href="/cmdb/userdetail-{{ row.id }}">{{ row.username }}</a></li> {% endfor %} </ul> </div> </div> </body>

点击用户跳转到用户详情页面
再去urls.py 找userdetail-n 看用户详情

视图函数views.py查看user_detail函数

userdetail.html
<!--右边菜单--> <div style="position: absolute;top:48px;left:210px;right: 0;bottom: 0;overflow: auto;"> <h1>用户详细信息</h1> <ul> {% for row in userdetail %} <h3>用户名:{{ row.username }}</h3> <h3>密码:{{ row.password }}</h3> <h3>uid: {{ row.id }}</h3> {% endfor %} </ul>

django models增删改示例
用户管理界面包含添加、编辑和删除按钮
userinfo.html
<head> <meta charset="UTF-8"> <title>Title</title> <style> .menu{ display: block; padding:5px; } </style> </head> <body style="margin: 0;"> <div style="height:48px;background-color: black;color: red;"> </div> <div> <!--左边菜单--> <div style="position: absolute;top:48px;left: 0;bottom: 0;width: 200px;background-color: red"> <a class="menu" href="/cmdb/userinfo">用户管理</a> <a class="menu" href="/cmdb/usergroup_info">用户组管理</a> </div> </div> <div> <!--右边菜单--> <div style="position: absolute;top:48px;left:210px;right: 0;bottom: 0;overflow: auto;"> <h1>用户列表</h1> <ul> {% for row in userlist %} <li> <a href="/cmdb/userdetail-{{ row.id }}">{{ row.username }}</a> | <a href="/cmdb/userdel-{{ row.id }}">删除</a>| <a href="/cmdb/useredit-{{ row.id }}">编辑</a> </li> {% endfor %} </ul> <h2>添加用户</h2> <form action="/cmdb/userinfo/" method="POST"> <input type="text" name="username"/> <input type="password" name="password"/> <input type="submit" value="添加"/> </form> </div> </div> </body>

urls.py

视图函数views.py
def user_del(request,uid): ###删除操作
models.UserInfo.objects.filter(id=uid).delete()
return redirect('/cmdb/userinfo')
def user_edit(request,uid): ##编辑操作
if request.method == 'GET':
user_infomation = models.UserInfo.objects.filter(id=uid)
return render(request,'edit.html',{"user_infomation":user_infomation})
elif request.method == 'POST':
user_id = request.POST.get('id')
uname = request.POST.get('username')
pwd = request.POST.get('password')
models.UserInfo.objects.filter(id=user_id).update(username=uname,password=pwd)
return redirect('/cmdb/userinfo')

edit.html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/html"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .menu{ display: block; padding:5px; } </style> </head> <body style="margin: 0;"> <div style="height:48px;background-color: black;color: red;"> </div> <div> <!--左边菜单--> <div style="position: absolute;top:48px;left: 0;bottom: 0;width: 200px;background-color: red"> <a class="menu" href="/cmdb/userinfo">用户管理</a> <a class="menu" href="/cmdb/usergroup_info">用户组管理</a> </div> </div> <div> <!--右边菜单--> <div style="position: absolute;top:48px;left:210px;right: 0;bottom: 0;overflow: auto;"> <h1>用户编辑</h1> {% for row in user_infomation %} <form action="/cmdb/useredit-{{ row.id }}/" method="POST"> <input style="display: none" type="text" name="id" value={{ row.id }} /> <input type="text" name="username" value={{ row.username }} /> <input type="text" name="password" value={{ row.password }} /> <input type="submit" value="提交"> </form> {% endfor %} </div> </div> </body> </html>


浙公网安备 33010602011771号