Adapt JSONField to have auto conversion to Decimal

465 views Asked by At

I have model with fields of type:

django.contrib.postgres.fields.JSONField

and I want have it always deserialized by:

json.loads(value, parse_int=decimal.Decimal, parse_float=decimal.Decimal)

when accessing objects by:

MyModel.objects.get(..)

however I found it hard to customize, because the line with json.loads which must be overriden by above one is in

psycopg2/_json.py

in inner method of def _create_json_typecasters.

so I am expecting to have to change my model fieldtype, or maybe there is a easier way to tell Django how to prepare my model?

1

There are 1 answers

0
Sławomir Lenart On

I found it:

psycopg2.extras.register_default_json(loads=my_loads_func)
psycopg2.extras.register_default_jsonb(loads=my_loads_func)  # for Postgres jsonb

or adapting it in more sophisticated way: psycopg2 docs