Mantis
Mantis

Reputation: 1387

iterate over model columns

How do i loop over all fields from a QuerySet. I need a list of all field values to export to a xlsx file but the columns can not be predefined with client.name for example.

If for loop objects, i just get the ID:

for i in Model.objects.all():
    print i

If i try to nest for loops, i get TypeError 'Model' object is not iterable.

for i in Model.objects.all():
        for y in i:
            print y

Upvotes: 0

Views: 462

Answers (1)

Shang Wang
Shang Wang

Reputation: 25539

for obj in Model.objects.all():
    for field in obj._meta.get_all_field_names():
        print getattr(obj, field)

However if you export to csv/xlsx, I won't recommend doing that, because there might be some fields that are ForeignKey or ManyToManyField, etc, so it's better to do it explicitly for each field.

Edit:

I just tried it myself but you might need getattr(obj, field, None) to show None on some of the fields that are empty, like OneToOneField.

Upvotes: 1

Related Questions