Skip to content

Instantly share code, notes, and snippets.

@smclenithan
Last active August 29, 2015 14:05
Show Gist options
  • Save smclenithan/0cf91111d472f2a7970a to your computer and use it in GitHub Desktop.
Save smclenithan/0cf91111d472f2a7970a to your computer and use it in GitHub Desktop.
CompressedTextField Django Model Field
# Simple wrapper over the BinaryField. Assumes it is given text and automatically compresses
# and decompresses upon access. Intended as a space saving mechanism on what
# would normally be bulk text that isn't accessed very often.
# Tested on Python3.4 / Django 1.7
from django.db import models
from django.utils.translation import ugettext_lazy as _
import lzma
class CompressedTextField(models.BinaryField, metaclass=models.SubfieldBase):
description = _("LZMA Compressed Text for BinaryFields")
empty_values = [None, b'']
def get_db_prep_value(self, value, connection, prepared=False):
if value is not None:
return lzma.compress(value.encode())
return value
def value_to_string(self, obj):
return lzma.decompress(self._get_val_from_obj(obj)).decode()
def to_python(self, value):
if value is not None:
if not type(value) in (str,):
return lzma.decompress(value).decode()
else:
return value
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment