You can create properties on the model, which will make the key:value pairs in that dict appear as if they are ordinary model fields for a lot of coding purposes (but not querysets or ModelForms)
In passing I'd really really want to change results to a JSONfield, but I'll assume you aren't using PostgreSQL ...
class ModelA(models.Model):
results = models.CharField(max_length=255)
@property
def name(self):
if not hasattr(self, '_rdict'):
self._parse_results()
return self._rdict['name']
@name.setter
def name( self, value):
if not hasattr(self, '_rdict'):
self._parse_results()
self._rdict['name'] = value
# similarly for the other keys in results
# if thre are lots of keys, to be DRY investigate the property builtin
# field = property( getter, setter)
def _parse_results(self):
d = OrderedDict()
# use self.results to turn results back into an OrderedDict
# code (use python re module? ) tbs
# set d['name'] = parsed_name etc in the right order!
self._rdict = d
def save( self, *args, **kwargs):
# rewrite results to reflect _rdict contents
# this is a hack implementation
# (but I suspect it's how results is generated)
self.results = str( self._rdict)
super().save(*args, **kwargs)
If you just want to be able to read these values as if they were fields, but not update them back to the database, you can dispense with a lot of this:
class ModelA(models.Model):
results = models.CharField(max_length=255)
@property
def name(self):
if not hasattr(self, '_rdict'):
self._parse_results()
return self._rdict['name']
def _parse_results(self):
# as above
# def save( ...) is not needed if the properties are read-only
You might save all those hasattr tests if you instead decoded results in the model's __init__ after super().__init__ called. I don't know why, but the Django doc warns against this (or used to). I have done it with one of my models, and so far no ill consequences I am aware of. Interfering before the superclass does its magic may be what it was warning against. I can't find the warning now.
If you wanted to use (say) modelforms based on the "fields" in results. there's another way that might help: multi-table inheritance. I don't know enough to recommend this. It creates an automagical OneToOne relation between the current DB table and your new model. You'd then have to subclass the __init__ method of your model to decode the results. Good luck if you attempt this (and if you do get it working, post what you did back here as an answer to your own question, because I'd like to know! )