select value from jsonfield in queryset

Viewed 4135

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!

2 Answers

Don't use extra it might be deprecate for next versions as warning from django

Use RawSQL instead.

MyModel.objects.annotate(name=RawSQL("myfield->>'name'")).values('name').filter(<put your conditions here>)
Related