django select_related()和反射结合
对于有外键关联的表,select_related()会自动进行多变关联;
1 2 3 4 5 6 7 8 9 10 11 12 | ret = models.UserInfo.objects. all ().select_related() print ret.query SQL为: SELECT "app01_userinfo" . "id" , "app01_userinfo" . "user_type_id" , "app01_userinfo" . "username" , "app01_userinfo" . "age" , "app01_usertype" . "id" , "app01_usertype" . "caption" FROM "app01_userinfo" INNER JOIN "app01_usertype" ON ( "app01_userinfo" . "user_type_id" = "app01_usertype" . "id" ) |
针对单独查询出来的一条字段的对象,select_related()只支持多对多的对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | >>> from jasset.models import Asset, IDC, AssetGroup, ASSET_TYPE, ASSET_STATUS >>> aa = Asset.objects. all () >>> aa [<Asset: 172.16 . 158.2 >, <Asset: 172.16 . 158.3 >, <Asset: 10.88 . 10.5 >, <Asset: 172.16 . 10.4 >, <Asset: 10.88 . 10.6 >, <Asset: 10.88 . 10.8 >, <Asset: 10.88 . 10.7 >, <Asset: 192.168 . 1.4 >, <Asset: 192.168 . 1.3 >, <Asset: 192.168 . 1.11 >, <Asset: 192.168 . 1.1 >, <Asset: 10.90 . 1.1 >, <Asset: 192.168 . 1.9 >, <Asset: 10.90 . 1.2 >, <Asset: 192.168 . 1.13 >, <Asset: 192.168 . 1.5 >, <Asset: 192.168 . 1.6 >, <Asset: 192.168 . 1.7 >, <Asset: 192.168 . 1.9 >, <Asset: 192.168 . 1.10 >, '...(remaining elements truncated)...' ] >>> bb = aa[ 0 ] >>> bb.idc <IDC: 莱锦> >>> hasattr (bb.idc, 'select_related' ) False >>> hasattr (bb.group, 'select_related' ) #group字段是多对多关联的 True |
django orm与反射的结合:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #通过反射直接获取字段的值 >>> for n in aa: ... print getattr (n, 'hostname' ) ... 莱锦基础服务_158. 2 莱锦docker - 3_158 . 3 莱锦VirtualBox - 1_10 . 5 莱锦基础服务_10. 4 莱锦docker - 1_10 . 6 莱锦docker - 2_10 . 8 莱锦VirtualBox - 1_10 . 7 4 、 5 层AC控制器_192. 168.1 . 4 4 、 5 层AC控制器_192. 168.1 . 3 4 层接入交换机_F4 - SW3_192. 168.1 . 11 4 、 5 层出口路由器_192. 168.1 . 1 5 层核心交换机_10. 90.1 . 1 4 层汇聚交换机_F4 - SW1_192. 168.1 . 9 1 层核心交换机 5 层POE交换机_192. 168.1 . 13 5 层接入交换机_192. 168.1 . 5 5 层接入交换机_192. 168.1 . 6 5 层接入交换机_192. 168.1 . 7 4 层汇聚交换机_192. 168.1 . 9 5 层接入交换机_192. 168.1 . 10 5 层接入交换机_192. 168.1 . 11 5 层接入交换机_192. 168.1 . 12 4 层POE交换机_192. 168.1 . 8 3 层汇聚交换机_192. 168.4 . 31 3 层POE交换机_192. 168.4 . 30 1 层AC控制器_192. 168.4 . 3 1 层AC控制器_192. 168.4 . 4 1 层接入交换机_192. 168.4 . 10 1 层接入交换机_192. 168.4 . 11 1 、 3 层出口路由器_192. 168.4 . 1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | >>> for n in bb.group.select_related(): ... getattr (n, 'name' ) ... u '\u57fa\u7840\u670d\u52a1' >>> for n in bb.group.select_related(): ... ... print getattr (n, 'name' ) ... 基础服务 >>> bb.group.select_related() [<AssetGroup: 基础服务>] >>> >>> >>> >>> bb.group.select_related()[ 0 ] <AssetGroup: 基础服务> >>> >>> getattr (bb.group.select_related()[ 0 ], 'name' ) u'\u57fa\u7840\u670d\u52a1 |
注意:select_related(),查询的对象是列表,类似于filter查询出来的结果;
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步