Iterating through model fields - Django

百般思念 提交于 2020-01-01 04:19:09

问题


I'm trying to iterate through fields as they are written down within my model:

currently I'm using this:

def attrs(self):
  for attr, value in self.__dict__.iteritems():
    yield attr, value

but the order seems pretty much random :(


Any ideas?


回答1:


The _meta attribute on Model classes and instances is a django.db.models.options.Options which provides access to all sorts of useful information about the Model in question.

For fields, it will give you them in the order they were created (i.e. the same order they were declared).

def attrs(self):
    for field in self._meta.fields:
        yield field.name, getattr(self, field.name)


来源:https://stackoverflow.com/questions/3159614/iterating-through-model-fields-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!