How to filter nested fields in a JSONField using Django ORM with Djongo?

51 Views Asked by At

I am working on a Django project where I am using Djongo as an ORM for MongoDB. I have a model named ProcessIDs which contains a JSONField named data. Within this JSONField, there are nested fields, and I am trying to filter the model entities based on a nested field value. Specifically, I am looking to filter based on the value of data->redirect_ids->status.

I attempted to use the following query to filter the model entities:

active_processes = ProcessIDs.objects.filter(data__redirect_ids__status__exact='active')

I was expecting this query to return all ProcessIDs objects where the status field under redirect_ids nested within the data field is set to 'active'. However, executing this query resulted in a FieldError with the following message:

FieldError: Unsupported lookup ‘redirect_ids’ for JSONField or join on the field not permitted.

I am looking for a way to achieve the desired filtering using Django ORM with Djongo. Is there a specific syntax or method to filter based on nested field values within a JSONField in this setup?

from djongo import models as mongo_models

class ProcessIDs(mongo_models.Model):
    data = mongo_models.JSONField(max_length=1000, default=dict())
    # ... other fields ...

# Example object creation
process = ProcessIDs.objects.create(
    data={'redirect_ids': {'ids': ['1234567', '7654321'], 'status': 'active'}, "category_type": "custom"}
)

# Attempted query
active_processes = ProcessIDs.objects.filter(data__redirect_ids__status__exact='active')

0

There are 0 best solutions below