Last active
September 15, 2021 23:50
-
-
Save fortunto2/b4379b2dc6ebc9b0228539b9a8d96c6c to your computer and use it in GitHub Desktop.
Use pydantic with django jsonfield and custom classes
This file contains hidden or 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 fractions import Fraction | |
from pprint import pprint | |
from django.core import exceptions | |
from django.contrib.postgres.fields import JSONField | |
from psycopg2.extras import Json | |
import orjson | |
from pydantic.json import custom_pydantic_encoder | |
ENCODERS = { | |
Fraction: str, | |
Color: str | |
} | |
class MyEncoder(json.JSONEncoder): | |
def default(self, obj): | |
return custom_pydantic_encoder(ENCODERS, obj) | |
def pydantic_json_dumps(v): | |
""" | |
Use in Config: json_dumps = pydantic_json_dumps | |
:param v: | |
:return: | |
""" | |
return json.dumps(v, cls=MyEncoder) | |
class JsonAdapter(Json): | |
""" | |
Customized psycopg2.extras.Json to allow for a custom encoder. | |
""" | |
def __init__(self, adapted, dumps=None, encoder=None): | |
self.encoder = encoder | |
super().__init__(adapted, dumps=dumps) | |
def dumps(self, obj): | |
return pydantic_json_dumps(obj) | |
class PydanticJSONField(JSONField): | |
def validate(self, value, model_instance): | |
super().validate(value, model_instance) | |
try: | |
pydantic_json_dumps(value) | |
except TypeError: | |
raise exceptions.ValidationError( | |
self.error_messages['invalid'], | |
code='invalid', | |
params={'value': value}, | |
) | |
def get_prep_value(self, value): | |
if value is not None: | |
return JsonAdapter(value, encoder=self.encoder) | |
return value | |
def orjson_dumps(v, *, default): | |
# faster decoder | |
# https://pydantic-docs.helpmanual.io/usage/exporting_models/ | |
# orjson.dumps returns bytes, to match standard json.dumps we need to decode | |
# in Config use json_dumps = orjson_dumps | |
try: | |
return orjson.dumps(v, default=default).decode() | |
except Exception as e: | |
return pydantic_json_dumps(v) |
This file contains hidden or 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
class BaseEntity(BaseModel): | |
class Config: | |
extra = Extra.ignore | |
json_loads = orjson.loads | |
json_dumps = orjson_dumps | |
use_enum_values = True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
use PydanticJSONField for django model