Storing serialized object in a Django model field

This is a personal solution to the fore stated problem.

I wanted to keep a syndicated data (dictionary) in a text column, no ordering or filtering operations needed, just bare storage. I am going to override both constructor and save() method to sync the record with an object property, holding the data. The code is pretty self-explanatory.

The only problem is the fact that you will not be able to edit the field in standard Django admin.

class MyModel(models.Model):
    details_map_field = models.TextField(editable=False) # since it will not work anyway
    # and many other fields you may have ..
 
    def __init__(self, *args, **kw):
        # here we hold the object. My object is a simple dict, holding some indexed details
        self.details_map = {}
        super(MyModel, self).__init__(*args, **kw)
        if self.details_map_field:
            # load object from serialized value in field
            self.details_map = json.loads(self.details_map_field)
 
    def save(self, *args, **kw):
        # always add/change values in details_map_field, save() will do the sync with the db
        self.details_map_field = json.dumps(self.details_map)
        super(MyModel, self).save(*args, **kw)
 
    def ppdetails(self):
        """ Pretty print """
        # this can be used in templates, as an interface to the actual data in field
        dets = json.loads(self.details_map_field)
        if len(dets):
            ret = ['%s: %s' % (k, v) for (k, v) in dets.items()]
            return '\n'.join(ret)
        else:
            return ''
 
>>> example = MyModel()
>>> example.details_map['age'] = 23
>>> example.details_map['gender'] = 'male'
>>> example.save()
>>> print example.ppdetails()
age: 23
gender: male
>>> print example.details_map_field # this should be invisible and should not be used
{"gender": "male", "age": 23}

  • http://profile.yahoo.com/42CSSDN56INFWUXKXSZWX554CI drbr

    Neat… fairly simple and useful solution.

    • http://twitter.com/mihneasim Mihnea Simian

      Thanks!

  • hei!

    Hi,

    I’ve tried your code and there is a small error for Django 1.3. This website shows how to solve it:

    http://semi-legitimate.com/blog/item/django-save-got-an-unexpected-keyword-argument-forceinsert

    • http://twitter.com/mihneasim Mihnea Simian

      You are right, my mistake, overwritten “save” should accept any parameters defined by original. I updated, thank you!