如何在Django中动态过滤字段名称,条件和值

问题描述 投票:0回答:1

我有一个要求,那就是从客户端获得一个对象数组,这些对象将具有字段名称,过滤条件和类似的过滤值。

对象的示例数组:

[
 {field_name: "book_name", filter_condition: "contains", filter_value: "some book name"},
 {field_name: "book_category", filter_condition: "not_equal", filter_value: "category value"},
 {field_name: "book_author", filter_condition: "starts_with", filter_value: "authoer name"},
 {field_name: "book_price", filter_condition: "equal", filter_value: 100}
]

并且我必须根据以上所有条件进行过滤。考虑一下我有一个名为Book的模型,该模型位于对象数组中(即book_name,book_category,book_author,book_price)。我真的不明白如何为此编写逻辑。任何人都可以请您提供逻辑帮助。

谢谢你。

django django-rest-framework django-orm django-filter
1个回答
0
投票

您可以使用dict开箱请注意,您不需要条件,因此,作为一个字典,数组就足够了以下代码将引导您到达所需的位置。

conditions = [
 ("book_name", "contains",  "some book name"),
 ("book_category", "not_equal",  "category value"),
 ("book_author", "starts_with",  "authoer name"),
 ("book_price", "equal",  100)
]
def get_filter(values):
    name,condition,value = values
    key = f"{name}__{condition}"
    return key, value

filters = dict(map(get_filter,conditions))
qs = qs.filter(**filters)
© www.soinside.com 2019 - 2024. All rights reserved.