Categories
Python Answers

How to iterate over model instance field names and values in template with Django Python?

Spread the love

To iterate over model instance field names and values in template with Django Python, we can use a queryset serializer.

For instance, we write

from django.core import serializers
data = serializers.serialize( "python", SomeModel.objects.all() )

to serialize the queryset results with serializers.serialize.

And then in our template, we write

{% for instance in data %}
    {% for field, value in instance.fields.items %}
        {{ field }}: {{ value }}
    {% endfor %}
{% endfor %}

to loop through the data list and get the values from instance.fields.items.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *