extra(额外,附加) -嵌套查询 """ select id , name , (select count(*) from tb2) as n from tb1 """ v = models.UserInfo.objects.all().extra( select={ 'n':"select count(*) from app01_usertype where id>%s or id<%s", #第一个嵌套 'm':"select count(*) from app01_usertype where id>%s or id<%s" #第二个嵌套 }, select_params=[1,2,3,4]) #多个占位符按顺序填写 for obj in v: print(obj.id,obj.name,obj.n) extra(额外,附加) -where 条件 v1 = models.UserInfo.objects.all().extra( where =["id=1","name='alex'"] ) print(v1.query) v2 = models.UserInfo.objects.all().extra( where=["id=1 or id=%s", "name=%s"], params=[1,"alex"] ) print(v2.query) extra(额外,附加) -多表查询 ,没有外键的表关联 笛卡尔积 v3 = models.UserInfo.objects.all().extra( tables=["app01_UserType"], where=["app01_UserInfo.ut_id = app01_UserType.id"] ) print(v3.query) extra(额外,附加) --全参查询样例 v4 = models.UserInfo.objects.all().extra( select ={'newid':"select count(*) from app01_usertype where id>%s"}, select_params=[1,], where=['age>%s',"app01_userinfo.ut_id=app01_usertype.id"], params=[18,], order_by=['-age'], tables=['app01_usertype'] ) print(v4.query)