0

I am using JSONField to store the configuration parameter(user_types) as a list as follows:

["user_type1", "user_type2", "user_type3"]

How to query to filter elements of type "user_type1"? The following query is not working:

rows=ConfigUserTable.objects.filter(user_types__in=["user_type1"])

Thanks

Kiran
  • 8,034
  • 36
  • 110
  • 176

1 Answers1

0

Use the contains lookup, which is overridden on JSONField. For example, the following may work:

ConfigUserTable.objects.filter(user_types__contains="user_type1")

However, this might depend on how you are storing JSON data in the field. If you are storing the data as a dict, querying on that key will certainly work. I.e. data in this format in the field user_types:

{"types": ["user_type1", "user_type2", "user_type3"]}

could be queried like so:

ConfigUserTable.objects.filter(user_types__types__contains="user_type1")

Reference: https://docs.djangoproject.com/en/dev/topics/db/queries/#std:fieldlookup-jsonfield.contains

ropable
  • 1,547
  • 1
  • 19
  • 31