Home > Back-end >  How to access nested fields in JSONField in the HTML template (Django)
How to access nested fields in JSONField in the HTML template (Django)

Time:01-20

I have a user model with a field called data containing nested data, e.g for one user that could be

data = {
      "2020":{"payment_date":"today","amount":600},
      "2021":{"payment_date":"","amount":800}
        }

the model also has a name field.

In my HTML I can access name and data but I struggle getting "deeper" into data to extract amount from 2020 and 2021.

I would assume I could do {{user.data.2020}} but that does not work. Doing {{user.data}} does indeed show the "remaining data".

Right now I have tried


<div >

    <table>
        <tr>
            <th>Name</th>
            <th>2020</th>
            <th>2021</th>
        </tr>
        {% for user in users%}
        <tr>
            <td>{{user.name}}</td>  # works
            <td>{{user.data.2020.amount}}</td> 
            <td>{{user.data.2021.amount}}</td>
        </tr>
        {% endfor %}

    </table>
</div>

but that does not work

CodePudding user response:

As another idea you can also use custom templatetags instead of a loop:

templatetags/dictionary_item.py

from django import template
register = template.Library()


@register.filter
def dictionary_item(dic, itm):
    return dic.get(itm)

And in your template:

{% load dictionary_item %}

<div >

    <table>
        <tr>
            <th>Name</th>
            <th>2020</th>
            <th>2021</th>
        </tr>
        {% for user in users%}
        <tr>
            <td>{{user.name}}</td>  # works
            <td>{{user.data|dictionary_item:"2020"|dictionary_item:"amount"}}</td> 
            <td>{{user.data|dictionary_item:"2021"|dictionary_item:"amount"}}</td>
        </tr>
        {% endfor %}

    </table>
</div>
  • Related