[Answer]-Looping through models in Django and getting column names and .get_FOO_display by default

1👍

Try something like:

# add to your Client model    
def get_fields(self):
    fields_display = []
    for f in Client._meta.fields:
        name = f.name        
        if len(f.choices) == 0:
            fields_display.append([name, f.value_to_string(self)])
        else:
            fields_display.append([name, getattr(self,"get_%s_display" % name)()])

   return fields_display

You can then loop over get_fields in your template for a given object

👤JamesO

0👍

If you want to get get_FOO_display by default, you have to overwrite the __getattribute__ method. Try something like this:

class FooModel(models.Model):
    ...
    def __getattribute__(self, item):
        get = lambda i: object.__getattribute__(self, i)
        name_map = get('_meta')._name_map

        if item.startswith('_') or name_map.has_key(item):
            return get(item)

        else:
            field = name_map.get(item)
            if field.choices:
                return get('get_%s_display' % item)()

            else:
                return get(item)

Leave a comment