pythondjangodjango-hstore

How do we query nested dictionary in django-hstore?


I have this stored in my serializedDictionaryField:

data = {
    'k1': 'v1',
    'k2': 'v2',
    'k3': {'nested_k': 'nested_v'}
}

Is it possible to filter by values of nested dictionary? something like

Model.objects.filter(data__contains={'nested_k': 'nested_v'})

Solution

  • HStoreField is just mapping string to string and does not support nested structure, you can use rather JSONField which come as built-in Posgres Field in Django 1.9+ and posgres 9.4+.

    models.py:

    from django.db import models
    from django.contrib.postgres.fields.jsonb import JSONField
    class MyModel(models.Model):
        ...
        data = JSONField(blank=True, null=True, default=dict)
    

    views.py:

    MyModel.objects.filter(data__k3__contains={'nested_k': 'nested_v'})