Skip to content

Commit 6dcd40b

Browse files
committed
use converters API rather than from_db_value()
1 parent c475a78 commit 6dcd40b

File tree

2 files changed

+9
-18
lines changed

2 files changed

+9
-18
lines changed

django_mongodb/fields/json.py

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
1-
import json
2-
31
from django.db import NotSupportedError
4-
from django.db.models import JSONField
52
from django.db.models.fields.json import (
63
ContainedBy,
74
DataContains,
@@ -28,20 +25,6 @@ def data_contains(self, compiler, connection): # noqa: ARG001
2825
raise NotSupportedError("contains lookup is not supported on this database backend.")
2926

3027

31-
_from_db_value = JSONField.from_db_value
32-
33-
34-
def from_db_value(self, value, expression, connection):
35-
"""
36-
Transforms the value retrieved from the database into a string if the database
37-
vendor is MongoDB. This is necessary because MongoDB saves the data as a
38-
dictionary, and converting it to a JSON string allows for proper decoding.
39-
"""
40-
if connection.vendor == "mongodb":
41-
value = json.dumps(value)
42-
return _from_db_value(self, value, expression, connection)
43-
44-
4528
def has_key_lookup(self, compiler, connection):
4629
rhs = self.rhs
4730
lhs = process_lhs(self, compiler, connection)
@@ -155,7 +138,6 @@ def register_json_field():
155138
HasKeyLookup.as_mql = has_key_lookup
156139
HasKeys.mongo_operator = "$and"
157140
JSONExact.process_rhs = json_process_rhs
158-
JSONField.from_db_value = from_db_value
159141
KeyTransform.as_mql = key_transform
160142
KeyTransformIn.as_mql = key_transform_in
161143
KeyTransformIsNull.as_mql = key_transform_isnull

django_mongodb/operations.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,8 @@ def get_db_converters(self, expression):
7575
converters.append(self.convert_datetimefield_value)
7676
elif internal_type == "DecimalField":
7777
converters.append(self.convert_decimalfield_value)
78+
elif internal_type == "JSONField":
79+
converters.append(self.convert_jsonfield_value)
7880
elif internal_type == "TimeField":
7981
converters.append(self.convert_timefield_value)
8082
elif internal_type == "UUIDField":
@@ -97,6 +99,13 @@ def convert_decimalfield_value(self, value, expression, connection):
9799
value = value.to_decimal()
98100
return value
99101

102+
def convert_jsonfield_value(self, value, expression, connection):
103+
"""
104+
Convert dict data to a string so that JSONField.from_db_value() can
105+
decode it using json.loads().
106+
"""
107+
return json.dumps(value)
108+
100109
def convert_timefield_value(self, value, expression, connection):
101110
if value is not None:
102111
value = value.time()

0 commit comments

Comments
 (0)