Skip to content

JSONField

Sicong edited this page May 12, 2021 · 3 revisions

JSONField

JSON Example:

# NullableJSONModel
        values = [
            {'a': 'b', 'c': 14},
            {
                'a': 'b',
                'c': 14,
                'd': None,
                'e': '"quoted"',
            },
            {'x': 'y'},
        ]
  • Quoted strings are NOT supported, like {'e': '"quoted"'}. The value will be saved, but lookups may not work as expected.

  • isnull lookup, if set to True, it will return a QuerySet for keys that are not exist and keys that have value None(null).

  • has_key lookup check the existence of a specific key. If the value of this key is null it will return an empty QuerySet.

  • exact lookup does NOT support value = None, NullableJSONModel.objects.filter(value__d=None) will return an empty QuerySet.

>>> NullableJSONModel.objects.filter(value__a__isnull=True).values()
<QuerySet [{'id': 3, 'value': {'x': 'y'}, 'value_custom': None}]>

>>> NullableJSONModel.objects.filter(value__a__isnull=False).values()
<QuerySet [{'id': 1, 'value': {'a': 'b', 'c': 14}, 'value_custom': None}, {'id': 2, 'value': {'a': 'b', 'c': 14, 'd': None, 'e': '"quoted"'}, 'value_custom': None}]>

>>> NullableJSONModel.objects.filter(value__d__isnull=False).values()
<QuerySet []>

>>> NullableJSONModel.objects.filter(value__d__isnull=True).values()
<QuerySet [{'id': 1, 'value': {'a': 'b', 'c': 14}, 'value_custom': None}, {'id': 2, 'value': {'a': 'b', 'c': 14, 'd': None, 'e': '"quoted"'}, 'value_custom': None}, {'id': 3, 'value': {'x': 'y'}, 'value_custom': None}]>

>>> NullableJSONModel.objects.filter(value__has_key='d')
<QuerySet []>
Clone this wiki locally