如何针对这种情况优化代码?

时间:2016-05-26 02:30:43

标签: python django django-models

我定义了几个Django模型,需要像下面那样处理字段值,代码是多余的

version = 'xxxx'

version_objs  = AP_Release_Version.objects.filter(ap_version__icontains=version)
for version_obj in version_objs:
    version_value = version_obj.ap_version
    ......

version_objs  = CP_Release_Version.objects.filter(cp_version__icontains=version)
for version_obj in version_objs:
    version_value = version_obj.cp_version
    ......

version_objs = GPS_Release_Version.objects.filter(gps_version__icontains=version)
for version_obj in version_objs:
    version_value = version_obj.gps_version
    ......

有没有办法优化代码,比如定义映射信息?感谢

map_info = {
    'ap_version'  : 'AP_Release_Version',
    'cp_version'  : 'CP_Release_Version',
    'gps_version' : 'GPS_Release_Version',
}

然后我可以这样做:

for key in map_info:
    version_objs  = map_info['key'].objects.filter(key__icontains=version)
    for version_obj in version_objs:
        version_value = version_obj.key

2 个答案:

答案 0 :(得分:1)

有一个想法,使用kwargs:

map_info = {
    'ap_version'  : AP_Release_Version,
    'cp_version'  : CP_Release_Version,
    'gps_version' : GPS_Release_Version,
}

for k, v in map_info.items():
    version_objs = v.objects.filter(**{'%s_icontains' %k : version})
    for version_obj in version_objs:
        version_value = version_obj.key

答案 1 :(得分:1)

看起来你有三个变量:对象,icontains和属性。因此,创建一个元组列表:

import collections
VersionInfo = collections.namedtuple('VersionInfo', 'obj icontains attrname')

Vinfos = [
    VersionInfo(AP_Release_Version, 'ap_version__icontains', 'ap_version'),
    VersionInfo(CP_Release_Version, 'cp_version__icontains', 'cp_version'),
    VersionInfo(GPS_Release_Version, 'gps_version__icontains', 'gps_version'),
]

for vinfo in Vinfos:
    kwargs = {vinfo.icontains : version }
    version_objs = vinfo.obj.objects.filter(**kwargs)

    for version_obj in version_objs:
        version_value = getattr(version_obj, vinfo.attrname)
        ...