python 前端参数不定的级联查询实现

葫芦的运维日志

下一篇 搜索 上一篇

浏览量 5043

2019/02/18 23:46


前端参数不定情况下的级联查询实现。

下拉选单有的可能选了,有的可能没选。

对应后端一般需要写多个方法来进行对应。

但通过字符串sql拼接可以巧妙的,用一个方法应对参数个数不定情况下的查询。

以下为前端传不定个数参数给后端,后端django通过sql拼接,实现不定参数的级联查询。         

关键语句:

operator = "AND operator='{0}'".format(cleaned_data['operator'])

class AlarmTable(APIMeta):
    def __init__(self, request):
        super(AlarmTable, self).__init__(request)
        self.form_class = forms.AlarmTable

    def handle(self, cleaned_data):
        start_time = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(cleaned_data['start_time'], '%Y-%m-%d %H:%M:%S'))
        end_time = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(cleaned_data['end_time'], '%Y-%m-%d %H:%M:%S'))
        operator = ''
        service_name = ''
        area_name = ''
        level = ''
        components = ''
        biz_name = ''
        if cleaned_data['operator'] != '':
            operator = "AND operator='{0}'".format(cleaned_data['operator'])
        if cleaned_data['service_name'] != '':
            service_name = "AND service_name='{0}'".format(cleaned_data['service_name'])
        if cleaned_data['area_name'] != '':
            area_name = "AND area='{0}'".format(cleaned_data['area_name'])
        if cleaned_data['level'] != '':
            level = "AND important_level='{0}'".format(cleaned_data['level'])
        if cleaned_data['component'] != '':
            components = "AND components='{0}'".format(cleaned_data['component'])
        if cleaned_data['biz_name'] != '':
            biz_name = "AND biz_name='{0}'".format(cleaned_data['biz_name'])

        sql = """SELECT dtEventTime,service_name,operator,biz_name,area,important_level,err_content,components
                 FROM test_table
               WHERE dtEventTime>='{0}' AND dtEventTime<='{1}' {2} {3} {4} {5} {6} {7} order by dtEventTime desc limit 5000
        """.format(start_time, end_time, operator, service_name, area_name, level, components, biz_name)
        data_rst = bk_data.send_request(sql)
        return data_rst

 

葫芦的运维日志

打赏

上一篇 搜索 下一篇
© 冰糖葫芦甜(bthlt.com) 2021 王梓打赏联系方式 陕ICP备17005322号-1