Opened 6 years ago
Closed 6 years ago
#29504 closed Cleanup/optimization (wontfix)
JSONField dictionary/object lookup using an "integer" key
Reported by: | Shaheed Haque | Owned by: | nobody |
---|---|---|---|
Component: | Documentation | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | Carlton Gibson | Triage Stage: | Accepted |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description (last modified by )
The documentation on performing queries inside JSONField values https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/#key-index-and-path-lookups says:
If the key is an integer, it will be interpreted as an index lookup in an array: >>> Dog.objects.filter(data__owner__other_pets__0__name='Fishy')
Note the specific mention of array. While this might be true, it is not the whole truth as applied to dict/object. For example, given a dict/object whose keys are strings (as always in JSON) but which look like integers:
"employee": { "415": { "email": "Sherlock.Holmes@acme.co.uk", "mobile": "0700 1234567",
how is one supposed to select the "415" bit? It turns out that the same syntax as for the array case applies:
Foo.objects.filter(snapshot__employee__415__mobile='0700 1234567')
This was not at all obvious to me at least, especially as if the "415" is looked up as the final key in the query, the syntax becomes very different:
Foo.objects.filter(snapshot__employee__has_key='415')
Since I wasted quite a bit of time on this, I thought it might be useful to strengthen the documentation in this area to clarify how to lookup:
- In arrays and dict/objects
- if the key is the final term in the query
- if the key is not the final term in the query
Change History (6)
comment:1 by , 6 years ago
Description: | modified (diff) |
---|
comment:2 by , 6 years ago
Triage Stage: | Unreviewed → Accepted |
---|---|
UI/UX: | unset |
Version: | 2.0 → master |
comment:3 by , 6 years ago
Cc: | added |
---|
comment:5 by , 6 years ago
Has patch: | set |
---|
comment:6 by , 6 years ago
Resolution: | → wontfix |
---|---|
Status: | new → closed |
Type: | Uncategorized → Cleanup/optimization |
Closing per discussion on PR.
OK, I'm going to provisionally accept this. If you can put together a patch we can have a look and see if there's a clarification to be made.
I'm half-minded to say
wontfix
since JSON keys must always be strings, and whilst, like'415'
, they might look like integers, there's no real ambiguity.But lets see what improvement you have in mind. :)