getattr关键字arg过滤

时间:2016-03-28 17:02:53

标签: python django python-3.x

假设我有:

        if self.model_name == 'Column':
            model_objects = model_objects.filter(stub__in=params)
        elif self.model_name == 'Person':
            model_objects = model_objects.filter(web_slug__in=params)
        elif self.model_name == 'Tag':
            model_objects = model_objects.filter(name__in=params)

是否有一种干净的方法可以使用getattr / setattr使其像

一样
def clean_cool_filter(model_name, search_param):
    # cool stuff


model_objects = clean_cool_filter('Column',  'stub')

我认为我正在努力将字符串转换为关键字args

谢谢

1 个答案:

答案 0 :(得分:1)

对karthikr的解决方案略有改进。

def clean_cool_filter(model_name, params):
    clause = {
        "Column": 'stub__in',
        "Person": 'web_slug__in', 
        "Tag": 'name__in'
    }.get(model_name)
    if clause:
        return {clause: params}
    else:
        return {}

我想这更安全。