2

I have a model like below. I would like to loop over all the fields inside a view to get field name and value of the field in the corresponding object.

class Company(models.Model):
    name = models.CharField(max_length=1000)
    website = models.CharField(max_length=1000)
    email = models.CharField(max_length=200)
    phone_number = models.CharField(max_length=100)
    city = models.CharField(max_length=1000)

3 Answers3

3

I had the same question and this answer helped me
The idea is you can turn a model object into a dict and then iterate over the dict

from django.forms.models import model_to_dict
...
result = Company.objects.get(id=7)
resultDict = model_to_dict(result)
for key, value in resultDict.items():
  print(f'key: {key} - value: {value}')
Paul
  • 409
  • 4
  • 12
1

Use the Model _meta API. In this case you want the get_fields method:

Company._meta.get_fields()

Reference: https://docs.djangoproject.com/en/1.10/ref/models/meta/#retrieving-all-field-instances-of-a-model

lufte
  • 1,283
  • 1
  • 11
  • 21
  • Here, I am looking for both field name and the value of that field in an object. – Jagadeesh Dondeti Mar 28 '17 at 16:43
  • After getting all the names you can retrieve the value of that field for an specific instance like this: `getattr(activity_instance, field_name)`. – lufte Mar 28 '17 at 17:01
  • `Company._meta.get_fields()` gives a tuple of all fields (types and **names**). Is it possible to **only** get the field names and pass it to a list? – Love Putin Not War Jun 07 '20 at 07:47
0

Try to serialize the QuerySet:

from django.core import serializers
from .models import YourModel

# inside the view
...
object_list = serializers.serialize("python", YourModel.objects.all())

for object in object_list:
    for field_name, field_value in object['fields'].items():
        print field_name, field_value