Advertisements
Here is the code:
if(order=="dsc"):
return sorted(qs, key=compare_function, reverse=True)
elif (order=="asc"): # asc
# return sorted(qs, key=lambda obj: obj.teacher.name)
return sorted(qs, key=compare_function)
else:
pass
def compare_function(obj):
if obj == None:
return "aaaaaaa"
if obj.teacher == None:
return "aaaaaaa"
else:
test = {"teacher": obj.teacher}
return test.get("teacher").name.lower()
What I expect is to pass some additional params to compare_function like below:
if(order=="dsc"):
return sorted(qs, key=compare_function(cls_name), reverse=True)
elif (order=="asc"): # asc
# return sorted(qs, key=lambda obj: obj.teacher.name)
return sorted(qs, key=compare_function(cls_name))
else:
pass
def compare_function(obj, cls_name):
if obj == None:
return "aaaaaaa"
if obj.teacher == None:
return "aaaaaaa"
else:
test = {"teacher": obj.teacher}
return test.get("teacher").name.lower()
But as I did this, no param was passed to compare_function. So the "obj" in compare_func will be None.
Then I tried to changed to
return sorted(qs, key=compare_function(obj, cls_name), reverse=True)
However, the interpretor complained the obj can’t be found this time.
How can I do?
Thanks.:)
p.s. I’m seeking for a general solution. :’)
>Solution :
You can pass a lambda as the key that invokes compare_function
with an extra argument:
key=lambda x: compare_function(x, cls_name)