djangodjango-postgresql

django jsonField filtering to get list of values from a specified key


I am storing millions of jsonFields as a field in my django model with the following structure:

for object #1:

   {
     "key_1": value1
   }

for object #2:

{
    "key_1": value2
}

and so on... How can I get an array of the values for key 1 simply through filtering?

[value1, value2...]


Solution

  • You can use KeyTransform, basically it allows you to extract a key in a JSONField and annotate you queryset with it. KeyTransform is not in the django docs.

    from django.contrib.postgres.fields.jsonb import KeyTransform
    
    list(Item.objects.annotate(key_1=KeyTransform("key_1", "json_field")).values_list("key_1", flat=True))