day20-Django3
---恢复内容开始---
1、补充
Form
- 验证
- 生成HTML标签
- (select标签的数据:来源于数据)
Model:
一对多
# 1,CEO 2,CIO 3,COO
class UserType(models.Model):
name = models.CharField(max_lenght=32)
class UserInfo(models.Model):
name = models.CharField(max_lenght=32)
pwd = models.CharField(max_lenght=32)
user_type = models.ForignKey('UserType')
1、查询用户类是CEO所有用户
q = UserInfo.objects.filter(user_type__name='CEO')
QuerySet
[对象,]
q[0].name
q[0].pwd
q[0].user_type.name
2、
q = UserInfo.objects.filter(user_type__name='CEO').values('name','pwd','user_type__name')
q
[{'name':'xxx','pwd': 'xxx','user_type__name':'xxx'}]
3、
q = UserInfo.objects.filter(user_type__name='CEO').value_list('name','pwd','user_type__name')
q
[(xx,xx,xx),]
补充:(select标签的数据:来源于数据)
choices = [
(1,'CEO'),
(2,'COO')
]
choices = UserType.objects.all().value_list('id','name')
from django import forms class IndexForm(forms.Form): c = [ (1,'CEO'), (2,'COO') ] # c = models.UserType.objects.all().values_list('id','caption') user_type_id = forms.IntegerField(widget=forms.Select(choices=c)) def index(request): form = IndexForm() return render(request, 'index.html', {'form': form})
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>Index</h1> {{ form.user_type_id }} </body> </html>
2、model操作 F/Q
F:
temp = salary+500
models.UserInfo.objects.filter().update(salary=temp)
update userinfo set salary=salary+500
from django.db.models import F
models.UserInfo.objects.filter().update(salary=F('salary')+500)
Q:
构造搜索条件
1、传参
models.UserInfo.objects.filter(id=123,name='alex')
2、传字典
d = {'id': 123, 'name':'alex'}
models.UserInfo.objects.filter(**d)
<input name='id' />
<input name='name' />
获取用户输入,并构造成字典:
models.UserInfo.objects.filter(**c)
3、传Q对象
models.UserInfo.objects.filter(Q对象)
from django.db.models import Q
# q1 = Q()
# q1.connector = 'OR'
# q1.children.append(('id', 1))
# q1.children.append(('id', 2))
# q1.children.append(('id', 3))
# models.Tb1.objects.filter(q1)
# con = Q()
#
# q1 = Q()
# q1.connector = 'OR'
# q1.children.append(('id', 1))
# q1.children.append(('id', 2))
# q1.children.append(('id', 3))
#
# q2 = Q()
# q2.connector = 'OR'
# q2.children.append(('status', '在线'))
#
# con.add(q1, 'AND')
# con.add(q2, 'AND')
#
# models.Tb1.objects.filter(con)
def index(request):
# for i in range(10):
# models.UserType.objects.create(caption='CE'+str(i))
# c = models.UserType.objects.all().count()
# print(c)
form = IndexForm()
from django.db.models import Q
"""
q1 = Q()
q1.connector = 'OR'
q1.children.append(('id', 1))
q1.children.append(('id', 2))
q1.children.append(('id', 3))
# 1 CE0
# 2 CE1
# 3 CE2
obj = models.UserType.objects.filter(q1)
for item in obj:
print(item.id,item.caption)
"""
con = Q()
q1 = Q()
q1.connector = 'OR'
q1.children.append(('id', 1))
q1.children.append(('id', 2))
q1.children.append(('id', 3))
q2 = Q()
q2.connector = 'OR'
q2.children.append(('caption', 'CE1'))
q2.children.append(('caption', 'CE2'))
con.add(q1, 'AND')
con.add(q2, 'AND')
obj = models.UserType.objects.filter(con)
for item in obj:
print(item.id,item.caption)
return render(request, 'index.html', {'form': form})
def add_user_type(request):
q = request.GET.get('q', None)
if q:
models.UserType.objects.create(caption=q)
return HttpResponse(q)
3、model多对多操作
- 创建
a. 方式一:
class B2G(models.Model):
b_id = models.ForeignKey('Boy')
g_id = models.ForeignKey('Girl')
class Boy(models.Model):
username = models.CharField(max_length=16)
class Girl(models.Model):
name = models.CharField(max_length=16)
b. 方式二:
class Boy(models.Model):
username = models.CharField(max_length=16)
# girl_set
class Girl(models.Model):
name = models.CharField(max_length=16)
b = models.ManyToManyField('Boy')
- 操作:
添加:
正向
g1 = models.Girl.objects.get(id=1)
g1.b.add(models.Boy.objects.get(id=1))
g1.b.add(1)
bs = models.Boy.objects.all()
g1.b.add(*bs)
g1.b.add(*[1,2,3])
反向
b1 = models.Boy.objects.get(id=1)
b1.girl_set.add(1)
b1.girl_set.add(models.Girl.objects.all())
b1.girl_set.add(*[1,2,3,4])
...
删除:
g1 = models.Girl.objects.get(id=1)
g1.b.clear() # 清空和girl ID=1所关联的所有数据
g1.b.remove(2)
g1.b.remove(*[1,2])
查询:
g1 = models.Girl.objects.get(id=1) # SQL
g1.b.all() # SQL
g1.b.filter().count()
b1 = models.Boy.objects.get(id=1)
b1.girl_set.all()
models.Girl.objects.all().values('id','name', 'b__username')
models.Boy.objects.all().values('id','username', 'girl__name')
*** _set就是反向操作。b__到达boy表
更新:
remove + add
利用原始sql实现
ORM:
python操作数据库模块:
MySQLdb
pymysql
原生SQL
# from django.db import connection
# cursor = connection.cursor()
# cursor.execute("""SELECT * from tb where name = %s""", ['Lennon'])
# row = cursor.fetchone()
具体点:http://www.cnblogs.com/wupeiqi/articles/5246483.html
4、中间件
配置文件:
MIDDLEWARE_CLASSES
写类:
process_request
process_view
process_exception
process_response
1.10
自建中间件会报错:
需要导入from django.utils import deprecation
类继承:
class M1(deprecation.MiddlewareMixin):
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Author: Aaron Shen from django.utils import deprecation from django.shortcuts import render,HttpResponse class M1(deprecation.MiddlewareMixin): def process_request(self, request): print('M1.process_request') return HttpResponse('123') def process_response(self,request,response ): print('M1.process_response') return response class M2(deprecation.MiddlewareMixin): def process_request(self, request): print('M2.process_request') # return HttpResponse('123') def process_response(self,request,response ): print('M2.process_response') return response
配置文件:
MIDDLEWARE =
原版本:
如果process_request中有return, 则所有的process_response执行一遍
- process_request(self,request) #请求时先执行这类中间件
- process_view(self, request, callback, callback_args, callback_kwargs) #在到达view以后在执行一遍这类中间件
- process_template_response(self,request,response) #views中的return 是render 是执行
- process_exception(self, request, exception) #报错是执行
- process_response(self, request, response) #返回时执行
5、缓存
6、信号
7、分页(公共插件)
作业:页码处理
---恢复内容结束---