Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through model fields - Django

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?

like image 540
RadiantHex Avatar asked Jul 01 '10 16:07

RadiantHex


1 Answers

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)
like image 137
Jonny Buchanan Avatar answered Oct 20 '22 10:10

Jonny Buchanan