Saturday, 20 September 2014

Accessing dictionary values from a list of dictionaries in django... Wait . What?

This post deals with a question that has already been answered on stackoverflow here . I had to google  a lot, trying to phrase the exact words that would lead to this result. So, I am explaining the answer here as well( apart from the link provided) for myself and the others who find this blog before facing that problem (or it's solution).


I was in a situation in which i had to display the details of some users on the admin page of my django app. The list of users can be obtained in 1 line :

                     users.objects.filter(#myfiltercriteria)

The queryset returned can be transformed to a list of dictionaries with :

                    users.objects.filter(#myfiltercriteria).values()


Now the problem was how to retrieve these values. The simpler way is to retrieving the required values in the view itself and compile it in a list and then use the built in template tag of django for list to access the elements. 

Okay, I maybe wrong depending on the use case. (I was wrong in my case, as I had to retrieve the SAME set of values for all the users.) 

The better and efficient way is to make custom template tags. For the sake of better explanation, let us access the name attribute of the users dictionary passed to a template. 

   So, the custom filter tag is (credits :culebron )
                 
                    @register.filter
                    def get_item(dictionary, key):
                    return dictionary.get(key)

So, inside your template, you would access the names like this :

                   for user in users:
                       {{ user|get_item:item.name }}

This is extremely useful and neat but is not offered by django by default.

For a reference to see how custom template tags are made see this


No comments:

Post a Comment