I
I
Ilyas2018-11-01 11:06:03
PostgreSQL
Ilyas, 2018-11-01 11:06:03

How to implement the #>> operator in django?

Django 1.11
Postgres 9.6
Hello, there is a table "table" and it has a field "field" where jsonb data types are added . When forming a request, I need to enter values ​​into it by nested keys, with a raw request there are no problems and something like this is obtained:

SELECT "table"."field" :: json#>>'{rootkey,nestedkey}' AS "nested_key" FROM "table"
WHERE "table"."param1" = value1;

The problem arises when I want to get something similar in django
MyModel.objects.filter(param1=value1).annotate(nested_key=RawSQL('"table"."field" :: json#>>\'{rootkey,nestedkey}\'', ()))

such a query generally works, but the use of RawSQL confuses me wildly, is it possible to somehow get rid of this, can I use F somehow in a special way?
PS: in reality, the request is much more complicated, in this pseudocode I just showed the problem that exists in the real request.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yeletsky, 2018-11-01
@Tiendil

RawSQL and SQL queries in general should not be embarrassed :-) this is quite a normal practice.
ORMs are made to simplify life, but if we simplify something, then something will definitely become more complicated. In the case of ORM, non-standard queries become more complicated. If you start adding extensions for ORM, then working with it can become more difficult than generating SQL queries and all profit will be lost.
Therefore, in my opinion, it is more correct to write complex queries in SQL, and make simple ones using ORM, if it is more convenient.
PS With complex queries, Django ORM slows down significantly on its own (due to harsh internal logic). The Django developers are fixing this, but very slowly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question