-
-
Save cddumanov/682d96b49f49ddef02ffc4552b0fbe0e to your computer and use it in GitHub Desktop.
Updated version od Django CompressedJSONField
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
) |
Author
cddumanov
commented
Oct 21, 2020
- 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