2

In django 1.9(using postgresdb), we're using JSONField(in a model) whose entries looks something like this:

**Entry 1**(in a row of that table):
data: {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
  "key4": "value4"
}

**Entry 2**(in a row of that table):
data: {
  "key5": "value4",
  "key6": "value2",
  "key7": "value2",
  "key8": "value4"
}

I want to query in for values, something like data__value__contains='value4'

Django has support for "keys"(has_key, has_any_keys, has_keys) related queries

What would be good approach to query for above need ?

karthikr
  • 97,368
  • 26
  • 197
  • 188
Neo
  • 5,070
  • 10
  • 46
  • 65

1 Answers1

0

How about using an HStoreField instead of a JSONField, which then gives you access to a values lookup.

MyModel.objects.filter(data__values__contains='value4')

As stated in the Django docs, JSON Field only has these lookups:

Containment and key operations¶

JSONField shares lookups relating to containment and keys with HStoreField.

  • contains (accepts any JSON rather than just a dictionary of strings)
  • contained_by (accepts any JSON rather than just a dictionary of strings)
  • has_key
  • has_any_keys
  • has_keys
Adam Hopkins
  • 6,837
  • 6
  • 32
  • 52