我在 Django 1.5.4 和 PostgreSQL 9.3 中工作,将 django-jsonfield 用于 JSONField。
以下查询引发 db 错误(无法识别 json 类型的相等运算符):
ModelWithJsonField.objects.annotate(count=Count('field_to_count_by'))
field_to_count_by
不是 JSONField,而是普通的 int 字段。任何想法如何解决问题并仍然使用注释?
引擎盖后面有什么注释?
最佳答案
我遇到了同样的问题,最后(今天)通过在 psql 控制台中以管理员身份运行来实现一个假操作符:
-- This creates a function named hashjson that transforms the
-- json to texts and generates a hash
CREATE OR REPLACE FUNCTION hashjson(
json
) RETURNS INTEGER LANGUAGE SQL STRICT IMMUTABLE AS $$
SELECT hashtext($1::text);
$$;
-- This creates a function named json_eq that checks equality (as text)
CREATE OR REPLACE FUNCTION json_eq(
json,
json
) RETURNS BOOLEAN LANGUAGE SQL STRICT IMMUTABLE AS $$
SELECT bttextcmp($1::text, $2::text) = 0;
$$;
-- This creates an operator from the equality function
CREATE OPERATOR = (
LEFTARG = json,
RIGHTARG = json,
PROCEDURE = json_eq
);
-- Finaly, this defines a new default JSON operator family with the
-- operators and functions we just defined.
CREATE OPERATOR CLASS json_ops
DEFAULT FOR TYPE json USING hash AS
OPERATOR 1 =,
FUNCTION 1 hashjson(json);
(深受 this 线程启发)
我还在 django-jsonfield GitHub issue 中引用了您的问题。
注意:
关于python - Django 数据库错误 : could not identify an equality operator for type json when trying to annotate a model with jsonfield,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19117933/