简体   繁体   English

遍历模型列

[英]iterate over model columns

How do i loop over all fields from a QuerySet . 我如何遍历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. 我需要所有字段值的列表以导出到xlsx文件,但是无法使用例如client.name来预定义列。

If for loop objects, i just get the ID: 如果对于循环对象,我只获得ID:

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

If i try to nest for loops, i get TypeError 'Model' object is not iterable . 如果我尝试嵌套循环, TypeError 'Model' object is not iterable得到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. 但是,如果您导出到csv / xlsx,则我不建议您这样做,因为可能会有某些字段为ForeignKeyManyToManyField等,因此最好对每个字段进行显式处理。

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 . 我只是自己尝试过,但是您可能需要getattr(obj, field, None)在某些空字段上显示None ,例如OneToOneField

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM