How to Filter + select json inside Jsonfield in django-rest-framwork
In one colomn response is store like this :-
Now i want to filter this response
[
{
"id": "A",
"children": [
{
"id": "propertyName#0",
"index": 0,
"label": "Property",
},
{
"id": "userName#0",
"index": 1,
"label": "Reported By",
},
{
"id": "textinput#0",
"index": 2,
"label": "Reported By Title",
},
{
"id": "dateinput",
"index": 3,
"label": "Date Reported",
}
],
"component": "sectionDivider"
},
{
"id": "B",
"children": [
{
"id": "propertyName#0",
"index": 0,
"label": "Property",
},
{
"id": "userName#0",
"index": 1,
"label": "Reported By",
},
{
"id": "textinput#0",
"index": 2,
"label": "Reported By Title",
},
{
"id": "dateinput",
"index": 3,
"label": "Date Reported",
}
],
"component": "sectionDivider"
},
{
"id": "C",
"children": [
{
"id": "propertyName#0",
"index": 0,
"label": "Property",
},
{
"id": "userName#0",
"index": 1,
"label": "Reported By",
},
{
"id": "textinput#0",
"index": 2,
"label": "Reported By Title",
},
{
"id": "dateinput",
"index": 3,
"label": "Date Reported",
}
],
"component": "sectionDivider"
}
]
I want to filter like this how can i get this response
I have id for the check like id: "A", id :"B" should only filter A and B and inside A and B i also want to filter.
[
{
"id": "A",
"children": [
{
"id": "propertyName#0",
"index": 0,
"label": "Property",
}
],
"component": "sectionDivider"
},
{
"id": "B",
"children": [
{
"id": "propertyName#0",
"index": 0,
"label": "Property",
},
{
"id": "userName#0",
"index": 1,
"label": "Reported By",
}
],
"component": "sectionDivider"
}
]
Till now i have tried django orm but unable to get expected output
Django ORM does provide support for nested queries inside the JSONField
.
Assuming your JSON field is defined like this:
class SomeModel(models.Model):
....
parent = JSONField()
The desired results can be achieved by using the ORM and the contains lookup:
SomeModel.objects.filter(
parent__contains=[{"id":"A", "children": [{"label": "Property"}]}, {"id":"B"}]
)
It's quite powerful and allows you to do nested filtering as well.
See how I used the children:label
filter along with the id
filter.