Ishan
Ishan

Reputation: 3395

Django 1.10 Postgres JSONField extract specific keys

I have a Postgres based JSONField in my model.

class MyModel(models.Model):
    data = JSONField(default=dict)

The JSON sample is like:

{
    'key1': 'val1',
    'key2': 'val2'
}

I have multiple objects of the model, let's say ~50.

I am trying to query for only the key1 inside data and want to get a list of all the distinct values of the key1.

How can I do that? Please note I am using Django 1.10.

Upvotes: 0

Views: 731

Answers (2)

Shaumux
Shaumux

Reputation: 745

You can use KeyTransform for that

MyModel.objects.annotate(key1=KeyTransform('key1', 'data')).distinct('key1').values_list('key1', flat=True)

Upvotes: 1

badiya
badiya

Reputation: 2257

You can try using has_key

items=MyModel.objects.filter(data__has_key='key1').values_list('data',flat=True)
new_list=[]
for item in items:
    new_list.append(item['key1'])

dist_list=list(set(new_list)) #list of distinct values.

Upvotes: 1

Related Questions