Menu Close

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

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.

Posted in Python, Python Answers