Last active
March 3, 2021 08:58
-
-
Save akkuman/484865f28364337769606ed6b2951054 to your computer and use it in GitHub Desktop.
drf框架里面的json字符串field改版,主要是针对model字段为text
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
import json | |
from rest_framework.fields import Field | |
from django.utils.translation import gettext_lazy as _ | |
class MyJSONField(Field): | |
default_error_messages = { | |
'invalid': _('Value must be valid JSON.') | |
} | |
def __init__(self, *args, **kwargs): | |
self.ensure_ascii = kwargs.pop('ensure_ascii', True) | |
self.encoder = kwargs.pop('encoder', None) | |
super().__init__(*args, **kwargs) | |
def to_internal_value(self, data): | |
if data is None: | |
return None | |
try: | |
return json.dumps(data, cls=self.encoder, ensure_ascii=self.ensure_ascii) | |
except (TypeError, ValueError): | |
self.fail('invalid') | |
return data | |
def to_representation(self, value): | |
if value is None: | |
return None | |
value = json.loads(value, cls=self.encoder) | |
return value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment