Skip to content
Advertisement

Django model filter targeting JSONField where the keys contain hyphen / dash

I am trying to apply a model filter on a JSONField BUT the keys in the JSON are UUIDs.

So when is do something like…

MyModel.objects.filter(data__8d8dd642-32cb-48fa-8d71-a7d6668053a7=‘bob’)

… I get a compile error. The hyphens in the UUID are the issue.

Any clues if there is an escape char or another behaviour to use? My database is PostgreSQL.

Update 1 – now with added JSON

{
   ‘8d8dd642-32cb-48fa-8d71-a7d6668053a7’: ’8d8dd642-32cb-48fa-8d71-a7d6668053a7’,
   ‘9a2678c4-7a49-4851-ab5d-6e7fd6d33d72’: ‘John Smith’,
   ‘9933ae39-1a27-4477-a9f4-3d1839f93fb4’: ‘Employee’
}

Advertisement

Answer

That’s looks difficult and I’m not 100% convinced what I have will work.

You can try using the JsonField contains lookup. The lookup is explained more under the docs for HStoreField since it’s shared functionality.

This would look like this:

MyModel.objects.filter(data__contains={'8d8dd642-32cb-48fa-8d71-a7d6668053a7': 'bob'})

I think this will allow you to circumvent the fact that the lookups need to be valid Python variable names.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement