Sławomir Lenart
Sławomir Lenart

Reputation: 8387

Adapt JSONField to have auto conversion to Decimal

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?

Upvotes: 0

Views: 478

Answers (1)

Sławomir Lenart
Sławomir Lenart

Reputation: 8387

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

Upvotes: 1

Related Questions