background
In the actual project, we will encounter the query conditions transmitted from the front end are not fixed, we can not use fixed query conditions to deal with.
As shown in the figure below, many conditions will be null, and the conditions with values are different each time they are passed, so we need to filter out the conditions with values.
So, how do you filter and how do you use the conditional data that you get after filtering to query?
solution
Because the value of the query field that the user does not select is empty value or empty string, we can traverse all fields, filter out the query condition, save it in the dictionary, and use the ** operator to dereference the dictionary during the query, then we can achieve the desired effect.
// filter throughdef getKwargs(data={}) :
kwargs = {}
for (k, v) in data.items():
if v is not None andv ! ="":
kwargs[k] = v
return kwargs
Copy the code
Query examples
Get data from the front end
projectName = request.POST["projectName"]
if projectName:
project = Project.objects.get(user=user, projectName=projectName)
else:
project = ""
user = User.objects.get(userId=userId)
startTime = request.POST["startTime"]
endTime = request.POST["endTime"]
# wrap the query criteria in dictionary form with the key name of the corresponding field in the database
DictCheck = son.loads(data)
dictCheck = {"user": user, "project": project, "createTime__gt": startTime, "createTime__lt": endTime}
dictFor = getKwargs(dictCheck)
Use ** dereference to query data conditions
tasks = RecognitialTask.objects.filter(**dictFor)
Copy the code