0

I have a model called Task that returns a date depending on the user. It defines a method:

def date_for_display(self, user):
  # return some date for the task

I want to create a list of tasks sorted by the date returned by this method. I tried something like:

user = User.objects.get(username="jamie")
sorted(Task.objects.all(), key = lambda task: task.date_for_display(user))

But to no avail. I get NameError: global name 'user' is not defined. Do I need to use a closure of some sort to accomplish this? Not sure how to go about doing it.

1 Answer 1

1

The easiest way to solve this is to use a keyword parameter in your lambda:

user = User.objects.get(username="jamie")
sorted(Task.objects.all(), key = lambda task, user=user: task.date_for_display(user))

This copies the user from the outer scope into the local scope of your lambda.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.