在django中动态追加带有日期范围运算符的列字段名称?

时间:2013-11-22 13:36:06

标签: python django

这是我正在使用的代码:

where_con=''
#loop on model name
# getting all info for one model
    where_con = {}
    for k in model_k_j:
        type_val = type(model_k_j[k])
        if type_val== dict:
            print "dictonary type"
            """
            for model_field_dict in model_k_j[k]:
                start= model_k_j[k][model_field_dict]
                end= model_k_j[k][model_field_dict]
                where_con[k] =  medical_home_last_visit__range=[start,end ]
                break
            """
        else:
            col_name.append(k)
            where_con[k] =  model_k_j[k] 
    # covert data type
    # **where_con {unpack tuple}
    # where_con =str(where_con)
    # print where_con
    qs_new = model_obj.objects.filter(**where_con)

字段medical_home_last_visit不是静态的,它是动态传递的。 我如何追加它?我尝试过类似的东西:

colname_variable =  medical_home_last_visit 
where_con[k] =  colname_variable + __range=[start,end ]

但它无法正常工作,并出现此错误:

where_con[k] =  colname_variable + __range=[start,end ]
                       ^
SyntaxError: invalid syntax

1 个答案:

答案 0 :(得分:1)

where_con是dict,密钥名称应该等于colname_variable__range

#k = 'medical_home_last_visit__range'
where_con[k] = (start, end)
qs_new = model_obj.objects.filter(**where_con)

等于:

model_obj.objects.filter(medical_home_last_visit__range=(start, end))

和任何其他过滤器参数应该是where_con中的键,例如:

#k = 'some_date__lte'
where_con[k] = datetime.datetime.now()