Django automatically compress Model Field on save() and decompress when field is accessed

Posted by Brian M. Hunt on Stack Overflow See other posts from Stack Overflow or by Brian M. Hunt
Published on 2010-03-31T15:34:16Z Indexed on 2010/04/04 11:53 UTC
Read the original article Hit count: 1069

Given a Django model likeso:

from django.db import models

class MyModel(models.Model):
    textfield = models.TextField()

How can one automatically compress textfield (e.g. with zlib) on save() and decompress it when the property textfield is accessed (i.e. not on load), with a workflow like this:


m = MyModel()
textfield = "Hello, world, how are you?"
m.save() # compress textfield on save
m.textfield # no decompression
id = m.id()

m = MyModel.get(pk=id) # textfield still compressed
m.textfield # textfield decompressed

I'd be inclined to think that you would overload MyModel.save, but I don't know the pattern for in-place modification of the element when saving. I also don't know the best way in Django to decompress when the field when it's accessed (overload __getattr__?).

Or would a better way to do this be to have a custom field type?

I'm certain I've seen an example of almost exactly this, but alas I've not been able to find it recently.

Thank you for reading – and for any input you may be able to provide.

© Stack Overflow or respective owner

Related posts about django

Related posts about django-orm