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!
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With