Answer the question
In order to leave comments, you need to log in
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;
MyModel.objects.filter(param1=value1).annotate(nested_key=RawSQL('"table"."field" :: json#>>\'{rootkey,nestedkey}\'', ()))
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question