首页 > 解决方案 > 为什么在使用 Array 字段的情况下 Django 不将 [] 或 SELECT 包装到 ARRAY?

问题描述

例如我有这样的查询:

Chat.objects.filter(users__contains=[user.pk]).filter(users__contained_by=mentors.values_list('pk', flat=True)) 

这就变成了这样的查询:

SELECT "chat_chat"."created_at", "chat_chat"."updated_at", "chat_chat"."id", "chat_chat"."users"
FROM "chat_chat"
 WHERE 
   ("chat_chat"."users" @> [1]::integer[] AND
    "chat_chat"."users" <@ (SELECT V0."id" FROM "users_user" V0
         INNER JOIN "users_userrequest_mentors" V1 ON (V0."id" = V1."user_id")
         WHERE V1."userrequest_id" IN
          (SELECT U0."id" FROM "users_userrequest" U0 WHERE U0."user_id" = 1))::integer[])

如果我运行这个查询,我将面临强制转换的问题。

不能将整数转换为整数 []

但是 Postgres 的文档说数组应该用作 ARRAY[1,2,...,4]
所以我已经将 [1] 和 (SELECT ...) 包装到 ARRAY 中

SELECT "chat_chat"."created_at", "chat_chat"."updated_at", "chat_chat"."id", "chat_chat"."users"
FROM "chat_chat"
 WHERE 
   ("chat_chat"."users" @> ARRAY[1]::integer[] AND
    "chat_chat"."users" <@ ARRAY(SELECT V0."id" FROM "users_user" V0
         INNER JOIN "users_userrequest_mentors" V1 ON (V0."id" = V1."user_id")
         WHERE V1."userrequest_id" IN
          (SELECT U0."id" FROM "users_userrequest" U0 WHERE U0."user_id" = 1))::integer[])

一切正常。
我只是好奇为什么 Django(或 psycopg2)会跳过这个包装。这种行为有什么特殊含义吗?

标签: arraysdjangopostgresqlpsycopg2

解决方案


推荐阅读