[Fixed]-Iterate over model columns

1👍

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.

Leave a comment