3

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'})
Dhia
  • 10,119
  • 11
  • 58
  • 69
waynetan413
  • 350
  • 1
  • 2
  • 10
  • I don't think you can do this. Postgres does not even support nested dictionaries. Keys and values are stored as text. http://www.postgresql.org/docs/current/static/hstore.html – Antoine Pinsard Mar 14 '16 at 12:51

1 Answers1

2

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'})
Dhia
  • 10,119
  • 11
  • 58
  • 69