Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map (apply function) Django QuerySet

Is there a mechanism to map Django QuerySet items not triggering its evaluation?

I am wondering about something like Python map. A function that uses a function to apply it over the QuerySet, but keeping the lazy evaluation.

For example, using models from Django documentation example, is there something like? (not real code):

>>> Question.objects.all().map(lambda q: q.pub_date + timedelta(hours=1))

which keeps the lazy evaluation?

like image 264
y.luis Avatar asked Sep 24 '17 22:09

y.luis


1 Answers

Just working through something like this myself. I think the best way to do it is to use a python list comprehension.

[q.pub_date + timedelta(hours=1) for q in Question.objects.all()]

Then Django takes care of optimizing this as it would any other query.

like image 60
JuanCaicedo Avatar answered Sep 26 '22 14:09

JuanCaicedo