Skip to content

Instantly share code, notes, and snippets.

@cddumanov
Forked from tomfa/fields.py
Last active October 21, 2020 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cddumanov/682d96b49f49ddef02ffc4552b0fbe0e to your computer and use it in GitHub Desktop.
Save cddumanov/682d96b49f49ddef02ffc4552b0fbe0e to your computer and use it in GitHub Desktop.
Updated version od Django CompressedJSONField
from django.utils.text import compress_string
from django.core.serializers.json import DjangoJSONEncoder
class CompressedJSONField(models.BinaryField):
compress = compress_string
encoder = DjangoJSONEncoder
@staticmethod
def uncompress(s):
zbuf = io.BytesIO(s)
with gzip.GzipFile(fileobj=zbuf) as zfile:
ret = zfile.read()
return ret
def is_binary(self, value):
return value and (type(value) == bytes or isinstance(value, memoryview))
def get_db_prep_save(self, value, connection=None):
if value is not None:
value = json.dumps(value, cls=self.encoder).encode('utf-8')
value = CompressedJSONField.compress(value)
return super().get_db_prep_save(value, connection)
def from_db_value(self, value, expression, connection):
if self.is_binary(value):
value = self.uncompress(value)
return json.loads(value.decode('utf-8'))
return value
from django.db import models
from fields import CompressedJSONField
class MyModel(models.Model):
price_points = CompressedJSONField(
null=True,
help_text='Accepts JSON, and stores compressed in database',
# encoder=MyCustomJSONEncoder
)
@cddumanov
Copy link
Author

  • fixed a bug that provoked recursion during delete
  • simplified logic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment