[Answered ]-Per instance dynamic fields django model

1👍

This question helped me find the solution: How do I override __getattr__ in Python without breaking the default behavior?

class GenericDocument(models.Model):
    def __getattr__(self, name):
        data = self.get_couchdb_data()
        if name in data.keys():
            return data[name]
        else:
            raise AttributeError

The dictionary returned by get_couchdb_data() is exposed as attributes of the model instance.

1👍

does this help:

class GenericDocument(models.Model):
...
@property
def sample_subfield(self):
    return self.json_field['sample_subfield']

That should work ok for known “sample_subfields” if there are not too many.

If you want to be able to call genericdocument.XXX (where XXX can be anything), then you would have to overwrite __getattribute__ in your model which I would not really put into consideratino since afaik Django does that itself.

Leave a comment