Django automatically compress Model Field on save() and decompress when field is accessed
- by Brian M. Hunt
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.