假设我们有以下过滤器:
filter1 = request.GET.get("blabla")
filter2 = request.GET.get("blabla")
filter3 = request.GET.get("blabla")
filter4 = request.GET.get("blabla")
filter5 = request.GET.get("blabla")
filter6 = request.GET.get("blabla")
假设我们有以下查询:
user_projects = Project.objects.filter(element1=filter1, element2=filter2, element3=filter3, element4=filter4, element5=filter5, element6=filter6).distinct().values("id", "name", "customer_id", "dev_status", "manager_id", "total_billable")
一些过滤器可能属于None
类型(取决于请求(
我想创建一个动态查询,根据过滤器是否存在,只使用非null过滤器执行查询。
例如,假设过滤器1、2和3有值,但过滤器4、5和6为空/空/无。
预期查询:
user_projects = Project.objects.filter(element1=filter1, element2=filter2, element3=filter3).distinct().values("id", "name", "customer_id", "dev_status", "manager_id", "total_billable")
我尝试过的:
if filter1 is None or filter1.strip() == "":
filter1 = ""
elif is_valid_queryparam(filter1):
user_projects = Project.objects.filter(element1=filter1).distinct().values("id", "name", "customer_id", "dev_status", "manager_id", "total_billable")
它是有效的,但只适用于一个过滤器,如果我想让6 or N
过滤器这样做,那么执行多个查询的效率非常低。
是否可以通过简单的查询来实现所需的结果?
您可以创建一个实用程序方法,如:
filter_qs_if_not_None(qs, **kwargs):
return qs.filter(
**{key: value for key, value in kwargs.items()if value is not None and value.strip()}
)
然后我们可以使用进行过滤
user_projects =filter_qs_if_not_None(
Project.objects.all(),
element1=filter1,
element2=filter2,
element3=filter3,
element4=filter4,
element5=filter5,
element6=filter6
)