Question

I came across this code inDjangobook. I am not able to understand what this means.

urlpatterns=pattern('django.views.generic',
                   url(r'^$','simple.direct_to_template',
                   kwargs={
                         'template':'index.html',
                         'extra_content':{'item_list':lambda:Item.objects.all()}
                          }
                   )

And in the template, simple iteration to display the items

{% for item in item_list %}

What is the purpose of lambda in the above url?

P.S: I know how lambda works in python (anonymous function). But I want to know what purpose it serves here. Why not have 'extra_content':{'item_list':Item.objects.all()}, since that will produce iterable anyway.

EDIT:

if i have

info_dict={'queryset':Item.objects.all()}

and pass this dict to extra_content

'extra_content':{'item_list':queryset}

would it be the same as lambda (I have seen this kind of example in the djangobook}

Was it helpful?

Solution

'extra_content':{'item_list':Item.objects.all()}

will be evaluated when the URLconf is loaded, so item_list will contain the same items for every request. Using a lambda tells Django to call that lambda for every request, meaning that items_list will change as new Items are added, removed, or edited in the database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top