python / intermediate
Snippet
Custom Django Model Field for Enforcing Validated JSON Storage
Custom Django model fields allow developers to control how Python data structures are serialized into database primitives and deserialized back into Python objects. Overriding to_python handles coercion and validation during model clean operations.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from django.db import modelsfrom django.core.exceptions import ValidationErrorimport jsonclass ValidatedJSONField(models.TextField):"""Stores dict objects as JSON strings with structural schema validation."""def to_python(self, value):if value is None or isinstance(value, dict):return valuetry:parsed = json.loads(value)if not isinstance(parsed, dict):raise ValidationError("JSON root content must be a dictionary object.")return parsedexcept json.JSONDecodeError as err:raise ValidationError(f"Invalid JSON payload syntax: {err}")def get_prep_value(self, value):if value is None:return valuereturn json.dumps(value)
django
Breakdown
1
class ValidatedJSONField(models.TextField):
Inherits from TextField to store data as text in the underlying relational database.
2
def to_python(self, value):
Converts raw database strings or input values into native Python dictionaries while validating formatting.
3
raise ValidationError("JSON root content must be a dictionary object.")
Ensures the decoded structure matches expected data types before saving to the instance.
4
def get_prep_value(self, value):
Transforms the Python dictionary into a JSON string prior to executing SQL query operations.