Reputation: 25597
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?
Upvotes: 14
Views: 8293
Reputation: 62813
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)
Upvotes: 24