Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

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

# inspired by : https://github.com/devkral/django-simple-jsonfield 

# MIT license 

 

 

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)