Django Json field filter throws lookup error
Asked Answered
B

1

10

I am using django postgres JSONfield and the model structure is as below

from django.contrib.postgres.fields import JSONField

class JsonAnswer(models.Model):
    name = models.CharField(max_length=255)
    data = JSONField(default={})

the data present in the Json field is as below

{
 "owner":{
    "name":"Bob",
    "other_pets":[
      {
       "name":"fishy"
      }
    ]
   },
 "bread":"lab"
}

and my filter query is like this

JsonAnswer.objects.filter(data__owner__name="Bob")

which is throwing the error

FieldError: Unsupported lookup 'owner' for JSONField or join on the field not permitted.

Please explain how to filter the json field data

Backhouse answered 21/9, 2017 at 6:20 Comment(1)
probably unrelated to your error but make sure when you set default value for a JSONField, use dict or dict() instead of {}, because it "creates a mutable default that is shared between all instances of JSONField".. see docsPelaga
U
0

In your code, above, you have the correct type of JSONField, but the error suggests that the column is not defined as jsonb in the database, for whatever reason (that's what the issue was for me when I encountered a similar error).

Underwing answered 27/12, 2018 at 23:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.