Posted By

magicrebirth on 12/22/09


Tagged

attribute model django


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

pjv


Django: access the attributes of a model dynamically


 / Published in: Django
 

example: a method on a model that outputs a list of tuples with (attributename.verbose, attributevalue)

  1. def attrs_verbose(self):
  2. model = self.__class__
  3. # using this form: Record._meta.get_field('created_by').verbose_name
  4. items = []
  5. for k, v in self.__dict__.items():
  6. try:
  7. x = model._meta.get_field(k).verbose_name
  8. except:
  9. x = k
  10. items += [(x, v)]
  11. items.sort()
  12. return items

Report this snippet  

You need to login to post a comment.