迭代通过模型领域 - Django [英] Iterating through model fields - Django

查看:104
本文介绍了迭代通过模型领域 - Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重复遍历字段,因为它们在我的模型中写下来



目前我使用的是: / p>

  def attrs(self):
for attr,value in self .__ dict __。iteritems():
收益attr,值

但是顺序似乎非常随机:(






任何想法?

解决方案

_meta 属性在模型类和实例是一个 django.db.models .options.Options 可以访问有关 Model 的各种有用信息。



对于字段,它将按照创建的顺序给他们(即它们被声明的顺序相同)。

  def attrs(self):
for self._meta.fields中的字段:
yield field.name,getattr(self,field.name)
/ pre>

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?

解决方案

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)

这篇关于迭代通过模型领域 - Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆