简体   繁体   中英

Django passing dictionary of tuples to template

If I made a set of code like this...

object_data = {}
object = Object.objects.all()
        for o in object:
            ratings = ObjectRating.objects.filter(recipe=r)
            counter = 0
            ratings_sum = 0

            for s in ratings:
                counter += 1
                ratings_sum += s.rating

            rating_average = ratings_sum / counter

            object_data[`o.id`] = (o, rating_average,)


        data = {
            'search_by' : search_by,
            'object' : object_data
        }

If I pass the data dictionary to the page ( render_to_response(page, data, context_instance=RequestContext(request)) ), how do I get the data from both parts of the tuple in the template.

This is how I thought I had to do it...

{% for o in object %}
       <tr><td>{{ o.0.name }}</td><td>{{ o.0.description }}</td><td>{{ o.0.other_col }}</td><td>{{ o.0.another_col }}</td><td>{{ o.1 }}</td></tr>
{% endfor %}

This is driving me insane and any insight will be helpful. This is Django 1.6 (I know I need to move on, so do not mention that in your answer).

Why not just add rating_average as an attribute to your object ?

for o in object:
    ... # calculate rating average for this object
    o.rating_average = ratings_sum / counter

data = {
        'search_by' : search_by,
        'object' : object
    }

{% for o in object %}
   <tr><td>{{ o.name }}</td>
       <td>{{ o.description }}</td>
       <td>{{ o.other_col }}</td>
       <td>{{ o.another_col }}</td>
       <td>{{ o.rating_average }}</td>
   </tr>
{% endfor %}

Like this example:

class HomeView(generic.TemplateView):
    template_name = '_layouts/index.html'
    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        mydict = {'wat': 'coo'}
        context['mydict'] = mydict
        return context

Template:

{% for key, value in mydict.items %}
  {{ key }} : {{ value }}
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM