Search code examples
djangomariadbdjango-orm

Django JSONField filter on complex JSON document with list of object


I work with Django 3.2 and MariaDB. I have an Product Model with an product_settings field (typed as JSONField ).

With a queryset I want to retrieve all products with a type of deposit equals to building.

Example of truncated product_settings value :

{
    "resources": [
        {
            "resource_config": {
                "linked_to": {
                    "params": {
                        "deposit": {
                            "type": "building"
                        }
                    }
                }
            }
        }
    ]
}

I'm trying with this queryset but it does not return any results :

Product.objects.filter(product_settings__resources__resource_config__linked_to__params__deposit__type="building")

Do you have any idea ?

I've already read this question but mine is quite more complex and need another solution.


Solution

  • Finally, I found the solution.

    I had to use __contains on resources key like this

    Product.objects.filter(
        product_settings__resources__contains={
            "resource_config": {
                "linked_to": {
                    "params": {
                        "deposit": {
                            "type": "building"
                        }
                    }
                }
            }
        }
    )