Ability to specify keys for JSONObject using arbitrary expressions

Currently there is no way to build a JSON object in the database using the JSONObject function where the keys are anything but static keys.

This is not a limitation of any of the backends that support JSON objects.

As an example esoteric usage, if you’re trying to get the database to emit valid objects for the Elasticsearch DSL, you would almost certainly need to be able to build objects with non-static keys.

For example ​https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html

The key “user.id” refers to a field in elastic.

See some discussion here: ​https://github.com/django/django/pull/19097#issuecomment-2611270246

“wontfix” feature request here: #36139 (Allow expressing JSONObject keys dynamically, as well as explicit pair-values) – Django

Pull request here: Fixed #36134 -- Add support for dynamic keys for JSONObject. by john-parton · Pull Request #19101 · django/django · GitHub

Is this a feature that anyone would actually use?

Thanks

Hey @john-parton

Worth noting: Looks like it could live as a project-level thing in the short run.

Is this a feature that anyone would actually use?

Could you motivate the use-case for me a little? I read the code: seems OK, but maybe for lack of :coffee: I’m struggling to engage my brain with when I want this new feature? (The elasticsearch example isn’t immediately transparent, at least to me, sorry)

Yes, it could be a project thing.

I’ve got a version of the code in my project which functions as described.

However, it has to either subclass the existing JSONObject function (annoying OO caveats) or copy/paste Django code to function (DRY/maintainability violation).

It turns out that there is some very annoying inconsistencies between the various DB backends.

Having it an official/included part of Django means it’s more likely to work automatically and correctly when using a 3rd party backend.

Regarding an actual example of when it might be useful, that’s where I’m less sure.

Let’s say you have an EAV table or something similar.

class Attribute(models.Model):
key = models.CharField()
value = models.CharField()

And an entry of “color”, “Red”

You might want the ability to produce documents like {“color”: “Red”}

1 Like

In the project I work on, the task to generate elasticsearch documents is one of the main performance bottlenecks we’re looking at improving. Pushing as much of the computation into the database is an attractive idea, and being able to use the ORM to do it, even better. I think we would need this feature to be able to do something that complex with the ORM. (But I’m saying this without having sketched it out to be certain.)

1 Like