Django.fun

Django filter json object's list by comparing with another list

I have a model that has a field which is a JSON field. This json_field has a value which is a list. The database used is Postgres

model: 
  attr1:
  attr2:
  attr3:
  json_field: {
      jattr1:
      jattr2:
      array_field: [values ...]
  }

I have a queryset obtained from some other filter operation: queryset

I want to apply model.objects.filter() such that I obtain every instance where array_field values are present in the queryset.

For example: consider 4 instances

instance1: 
  json_field: {
      array_field: [1, 2, 3, 4]
  }

instance2: 
  json_field: {
      array_field: [2, 4]
  }

instance3: 
  json_field: {
      array_field: [1, 4]
  }

instance4: 
  json_field: {
      array_field: [3]
  }

and queryset is :

queryset: [2, 3]

I am expecting something like this:

Model.objects.filter(json_field__array_field__in=queryset)

# This should return
instance1: 
  json_field: {
      array_field: [1, 2, 3, 4]
  }

instance2: 
  json_field: {
      array_field: [2, 4]
  }

instance4: 
  json_field: {
      array_field: [3]
  }

Thank you for your help.

Answers: 1

Answered by Prasanna, Oct. 13, 2021, 3:32 a.m.

the trick was to use __contains instead of __in so

Model.objects.filter(json_field__array_field__contains=queryset)

The above query does the job