Django automatically compresses the model field when saving () and unpacks when accessing the field

Given the Django model:

from django.db import models

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

How can I automatically compress textfield(for example zlib) on save()and unpack it when a property textfield(i.e. not when loading), with such a workflow:


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 would be inclined to think that you overloaded MyModel.save, but I do not know a template for modifying an element in place while saving. I also don't know how the best way in Django to unpack when a field is at its access (overload __getattr__?).

Or is the best way to do this: a custom field type ?

I am sure that I saw an example of almost this, but, alas, I could not find it recently.

Thanks for reading - and for any input you can provide.

+3
4

, , . . , , .

+2

. https://djangosnippets.org/snippets/2014/ ... TextField .

class CompressedTextField(models.TextField):
    """
    model Fields for storing text in a compressed format (bz2 by default)
    """
    __metaclass__ = models.SubfieldBase

    def to_python(self, value):
        if not value:
            return value

        try:
            return value.decode('base64').decode('bz2').decode('utf-8')
        except Exception:
            return value

    def get_prep_value(self, value):
        if not value:
            return value

        try:
            value.decode('base64')
            return value
        except Exception:
            try:
                tmp = value.encode('utf-8').encode('bz2').encode('base64')
            except Exception:
                return value
            else:
                if len(tmp) > len(value):
                    return value

                return tmp
0

Source: https://habr.com/ru/post/1739331/


All Articles