ORM之extra操作
ORM之extra操作
extra是实现复杂查找的方法。
实现类似这类复杂的查询:
""" select id, name, (select count(1) from tb) AS n FROM xb """
SQL语句的这类查询方式,用ORM的extra也是可以实现的。
""" select id, name, (select count(1) from tb) AS n FROM xb """ v = models.UserInfo.objects.all().extra(select={"n":"select count(1) from app01_usertype where id>%s and id<%s"},select_params=[1,2]) #extra 里面可以写一个字典,xb就是要关联的查询的表,比如是UserType。 select_params 里的参数可以是变量,app01_usertype就是xb的位置。 for obj in v: print(obj.name,obj.id,obj.n) #这个n就是select字典的key
既然select是个字典,那就可以不单单是一个n,也可以有多个,而select_params 的参数也是顺序延后就是啦。
""" select id, name, (select count(1) from tb) AS n FROM xb """ v = models.UserInfo.objects.all().extra( select={ "n":"select count(1) from app01_usertype where id>%s and id<%s", "n":"select count(1) from app01_usertype where id=%s OR id=%s", }, select_params=[1,2,3,4]) #extra 里面可以写一个字典,xb就是要关联的查询的表,比如是UserType。 select_params 里的参数可以是变量 for obj in v: print(obj.name,obj.id,obj.n) #这个n就是select字典的key
extra 里面可以用where,这个where是一个列表,列表的每个元素是通过 and 连接的。
models.UserInfo.objects.extra( where=["id=1","name='george'"] )
元素里面也可以有or和and条件。
models.UserInfo.objects.extra( where=["id=1 or id=2","name='george'"] )
但是where如果要动态传参,就需要和params组合来用。
models.UserInfo.objects.extra( where=["id=%s or id=%s","name='%s'"], params=[1,2,"george"] )
extra 里面也有order_by的排序:
models.UserInfo.objects.extra( where=["id=%s or id=%s","name='%s'"], params=[1,2,"george"], order_by=["-id"] #id 按倒序排列 )
extra 里面的tables 的方法:
tables是加表的意思
models.UserInfo.objects.extra( tables=["app01_usertype"], where=["app01_usertype.id = app01_userinfo.ut_id"], ) """ select * from app01_userinfo,app01_usertype where app01_usertype.id = app01_userinfo.ut_id """
如果不写where条件,那就是两张表查数据
models.UserInfo.objects.extra( tables=["app01_usertype"], ) """ select * from app01_userinfo,app01_usertype """
小总结:
select和select_params一起用:select 此处 from 表
where和params一起用:select * from 表 where 此处
tables用在:select * from 表,此处
order_by用在:select * from 表 order_by 此处
这几个条件可以在一个语句里面一起用:
models.UserInfo.objects.extra( select={"nid":"select count(1) from app01_usertype where id>%s"}, select_params=[1,], where=["age>%s"], #这个where是取UserInfo的值 params=[18], order_by=["-age"], tables=["app01_usertype"], ) # 那么这个ORM语句的原生SQL是这样的: """ select app01_userinfo.id (select count(1) from app01_usertype where id>%s) as nid from app01_userinfo,app01_usertype where app01_userinfo.age>18 order by app01_userinfo.age desc """
ORM写原生SQL语句:
from django.db import connection,connections cursor = connection.cursor() cursor = connections["default"].cursor() cursor.execute("select * from userinfo where id=%s",[1,]) v1 = cursor.fetchone() v2 = cursor.fetchall()
---------- END -----------