Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select value from jsonfield in queryset

I have the following situation

class MyModel(models.Model):
    my_field = JSONField(null=True, blank=True)

my_field is a JSON field with the following structure:

{
    "name": "some name"
    "id": "some hash id"
}

I want to perform something like: MyModel.objects.values(my_field__name)
which will be equivalent to the postgres query: select my_field->>'name' from my_app_my_model
but i can't seem to get django to generate the wanted query.
The error im getting is:

FieldError: Cannot resolve keyword 'name' into field. Join on 'my_field' not permitted.

The main goal here is to provide a list of strings called fields and run the following command: MyModel.objects.values(*fields) so i think that raw sql solutions won't fit here. Custom Lookups are for the WHERE clause and i don't know of any equivalent for the SELECT clause.
Any thought on how this can be done?
Thanks!

like image 998
Mr T. Avatar asked Jul 30 '17 13:07

Mr T.


1 Answers

Currently values doesn't support json lookups. You can try to do it with extra.

MyModel.objects.extra(select={'name':"my_field->>'name'"}).values('name')
like image 51
Dima Kudosh Avatar answered Oct 17 '22 02:10

Dima Kudosh