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
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.