Aman Gupta
Aman Gupta

Reputation: 1874

How to iterate over nested dictionaries and lists in django template

I am working with Google spreadsheets in Django. I have two models

class Workbooks(models.Model):
    name=models.CharField(max_length=100)

class Sheets(models.Model):
    name=models.CharField(max_length=100)
    workbook=models.ForeignKey(Workbooks)

I am in trouble getting this data on the template.I am looking to print list of workbooks and under each workbook i want its corressponding sheets i.e. Sheets.workbook_id=Workbooks.id

With this I am able to get the list of workbooks.What I want is to access the sheets model objects for each workbook.

{{% for name in workbooks%}}
 {{name}}
{{%endfor%}}

Upvotes: 1

Views: 233

Answers (1)

To achieve this you can use related object reference:

{% for workbook in workbooks %}
    {{ workbook.name }}<br />
    {% for sheet in workbook.sheets_set.all %}
        - {{ sheet.name }}<br />
    {% endfor %}
{% endfor %}

Upvotes: 1

Related Questions