【问题标题】:Django passing dictionary of tuples to templateDjango将元组字典传递给模板
【发布时间】:2015-04-13 01:39:22
【问题描述】:

如果我做了这样一组代码...

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
        }

如果我将数据字典传递给页面(render_to_response(page, data, context_instance=RequestContext(request))),我如何从模板中元组的两个部分获取数据。

这就是我认为我必须这样做的方式......

{% 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 %}

这让我发疯,任何见解都会有所帮助。这是 Django 1.6(我知道我需要继续前进,所以不要在你的回答中提及)。

【问题讨论】:

    标签: python django dictionary tuples


    【解决方案1】:

    为什么不将rating_average 作为属性添加到您的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 %}
    

    【讨论】:

    • 该死,当你看到这样的东西并且不得不面对手掌时,我喜欢它。非常感谢。
    【解决方案2】:

    像这个例子:

    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
    

    模板:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 2015-04-19
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      相关资源
      最近更新 更多