【问题标题】:How to properly unpack a nested dictionary in a django HTML template?如何正确解压缩 django HTML 模板中的嵌套字典?
【发布时间】:2021-12-30 00:21:31
【问题描述】:

所以我能够弄清楚如何将字典键和值解包到 HTML 模板中,但是如果字典值是 QuerySet,我对如何解包有点困惑。例如,我将给定用户的所有时间段传递到字典中。如何解包每个时间段的TimeSlot QuerySet的属性,例如开始时间和结束时间?

这是我的 HTML 模板:

<table>
    {% for key, value in user_info.items %}
        {% for key2,value2 in value.items %}
        <tr>
            <td>{{key2}}</td>
            <td>{{value2}}<td>
        </tr>
        {% endfor %}
        <br>
    {% endfor %}
    </table> 

views.py 中的函数

def check_food_availibility(request):
    food = FoodAvail.objects.all()
    timeslots = TimeSlot.objects.all()
    users_dict = {}
    for i in range(len(user_info)):
        user = {
            "author": None,
            "food_available": None,
            "description": None,
            "timeslot": None
        }
        user["author"] = user_info[i].author.username
        user["food_available"] = user_info[i].food_available
        user["description"] = user_info[i].description
        if TimeSlot.objects.filter(time_slot_owner=user_info[i].author):
            user["timeslot"] = TimeSlot.objects.filter(time_slot_owner=user_info[i].author)
        users_dict[user_info[i].author.username] = user

    return render(request, "food_avail/view_food_avail.html", {"user_info": users_dict})

这是它目前的显示方式:

【问题讨论】:

  • 您认为user_info 来自哪里?你能添加你的模型吗?您不需要创建字典并对其进行动态迭代,您知道它是键,因此您可以显式使用它们

标签: python python-3.x django


【解决方案1】:

试试这个

<table>
    {% for key, value in user_info.items %}
        {% for key2,value2 in value.items %}
        <tr>
            <td>{{key2}}</td>
          {% if key2 == 'timeslot' %}
           <td>
         {% for i in value2 %}

            i.start_time <-> i.end_time // just an example put your field here

         {% endfor %}
          
           </td>
          {% else %}
            <td>{{value2}}<td>
   
          {% endif %}
        </tr>
        {% endfor %}
        <br>
    {% endfor %}
    </table> 

【讨论】:

    猜你喜欢
    • 2014-03-04
    • 2011-10-11
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 2018-06-19
    • 2020-01-04
    • 1970-01-01
    • 2011-08-27
    相关资源
    最近更新 更多