fields.py 1.33 KB
Newer Older
1
2
3
# inspired by : https://github.com/devkral/django-simple-jsonfield
# MIT license

Florent Chehab's avatar
Florent Chehab committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

from django.core.exceptions import ValidationError
from django.db import models
import json


class JSONField(models.TextField):
    __qualname__ = "JSONField"
    __name__ = "JSONField"
    """ JSON field implementation on top of django textfield """

    def to_dict(self, value):
        """ convert json string to python dictionary """
        try:
            return json.loads(value)
        except json.decoder.JSONDecodeError as e:
            raise ValidationError(
                message=str(e),
                code="json_error"
            )

    def to_json(self, value):
        """ convert python dictionary to json string """
        return json.dumps(value)

    def from_db_value(self, value, expression, connection):
        """ convert string from db to python dictionary """
        if value is None:
            return value
        return self.to_dict(value)

    def to_python(self, value):
        """ convert model input value to python dictionary """
        if isinstance(value, (dict, list)):
            return value
        if value is None:
            return value
        return self.to_dict(value)

    def get_prep_value(self, value):
        """convert python dictionary to string before writing to db"""
        return self.to_json(value)