阿里山QQ

导航

django select_related()和反射结合

对于有外键关联的表,select_related()会自动进行多变关联;

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()只支持多对多的对象:

>>> 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与反射的结合:

#通过反射直接获取字段的值
>>> 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

  

>>> 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查询出来的结果;

posted on 2017-03-01 10:48  阿里山QQ  阅读(219)  评论(0编辑  收藏  举报