gpt4 book ai didi

python - 动态查询

转载 作者:行者123 更新时间:2023-11-29 12:54:51 26 4
gpt4 key购买 nike

我正在尝试寻找动态查询的最佳方式。项目前端会向后端发送json,通过参数查询获取对象:

Model.objects.filter(**query)

我可以根据自己的意愿设置 json 格式。在这一刻json:

# first case
{'type': 'channel_type', 'or': {'param1': {'__gte': 10}, 'param2': {'': 12}}}
# second case
{'type': {'in': ['channel1', 'channel2']}, 'and': {'p1': {'__lte': 12}, 'p2': {'!=': 1}}}

这在 sql 中将是相等的(从 y 中选择 x - 将是静态的,代码仅生成“where”条件):

# first case
WHERE table.type = channel_type AND (table.param1 >= 10 OR table.param2 = 12)
# second case
WHERE table.type IN [channel1, channel2] AND (table.p1 <= 12 AND table.p2 <> 1)

我已经这样做了:

query_params_dict = {'>': '__gt', '<': '__lt', '>=': '__gte', '<=': '__lte', '==': ''}

def parse_segmentation_query(query):
type = {'type': query.pop('type')} if isinstance(query['type'], str) else {'type__in': query.pop('type')['in']}
query = recursive_parsing_query(query)
query.update(type)
return query

Func "recursive_parsing_query"没有准备好,所以没有显示。但我想递归地从 dict 中弹出参数并生成 {'param1__gte': 2} dict,它将传入 **kwards 用于 objects.filter。问题是获得“不相等”条件 => 它破坏了简单编写的“Model.objects.filter(**query)”,因为我们需要“排除”。

我想知道:这种方式是否最适合动态查询?或者你可以提供更好的?如果没有,那么如何通过仅过滤条件排除?

更新:肯定 json-query 会更深

更新:

最后,我做到了(通过数字字段过滤进行动态查询),感谢 MJafar Mash:

condition_types = {'>': '__gt', '<': '__lt', '>=': '__gte', '<=': '__lte', '==': '', '!=': ''}
q_conditions = {'or': True, 'and': False}


def recursive_parsing_query(query, or_condition=False):
filter_obj = Q()
for key, value in query.items():
if key in q_conditions:
local_filter = recursive_parsing_query(value, q_conditions[key])
else:
local_filter = simple_parsing_query(key, value)
if or_condition:
filter_obj |= local_filter
else:
filter_obj &= local_filter
return filter_obj


def simple_parsing_query(parameter_name, parameter_query):
local_filter = Q()
for condition_type, condition_value in parameter_query.items():
parameter_condition = {parameter_name + condition_types[condition_type]: condition_value}
if condition_type != '!=':
local_filter = Q(**parameter_condition)
else:
local_filter = ~Q(**parameter_condition)
return local_filter

最佳答案

filterexclude 方式的启发 internally implemented ,我建议重写您的查询生成算法以使用 Q objects那么我想您不会对查询生成算法的否定或递归性有任何问题。

关于python - 动态查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46039653/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com