3

I have a simple model like:

class MyModel(models.Model):
    data = JSONField()

The JSONField data is in the following structure:

{
  "name": "Brian",
  "skills": [
     {"id": 4, "name": "First aid"},
     {"id": 5, "name": "Second aid"}
  ]
}

I'd like to create a query that gets a list of MyModels filtered by the id of the skill inside the data.

I've tried a few different avenues here, and can do the work in Python but I'm pretty sure there's a way to do this in Django; I think my SQL isn't good enough to figure it out.

Cheers in advance.

rahul.m
  • 5,572
  • 3
  • 23
  • 50

1 Answers1

2

try this

>>> MyModel.objects.filter(data__skills__contains=[{'id':4}, {'id':5}])

more about JSON filter https://docs.djangoproject.com/en/3.1/topics/db/queries/#querying-jsonfield

Dharman
  • 30,962
  • 25
  • 85
  • 135
rahul.m
  • 5,572
  • 3
  • 23
  • 50