Django: access the attributes of a model dynamically


/ Published in: Django
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.