Since you are writing Django code, you don't need lambdas at all (explanation below). In other Python code, you might want to use list comprehensions, as other commenters have mentioned. lambda
s are a powerful concept, but they are extremely crippled in Python, so you are better off with loops and comprehensions.
Now to the Django corrections.
tasks = Task.objects.all()
tasks
is a QuerySet
. QuerySet
s are lazy-evaluated, i.e. the actual SQL to the database is deferred to the latest possible time. Since you are using lambdas, you actually force Django to do an expensive SELECT * FROM ...
and filter everything manually and in-memory, instead of letting the database do its work.
contexts_to_display = ...
If those contexts are Django model instances, then you can be more efficient with the queries and fields instead of separate methods:
# tasks = Task.objects.all()
# tasks = filter(lambda t: t.matches_contexts(contexts_to_display), tasks)
# tasks = filter(lambda t: not t.is_future(), tasks)
# tasks = sorted(tasks, Task.compare_by_due_date)
qs = Task.objects.filter(contexts__in=contexts_to_display, date__gt=datetime.date.today()).order_by(due_date)
tasks = list(qs)
The last line will cause Django to actually evaluate the QuerySet
and thus send the SQL to the database. Therefore you might as well want to return qs
instead of tasks
and iterate over it in your template.
Task.objects.all()
line. \$\endgroup\$