我在 Django 1.5.4 和 PostgreSQL 9.3 中工作,使用 django-jsonfield对于 JSONField。
以下查询抛出数据库错误(无法识别 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 中引用了你的问题.
注意:
- 我对这会产生的影响非常有限。也许这不是一个好主意。这些实现是天真的,但它们应该足够了。也可能不是。
- 特别是,相等运算符检查文本相等性而不是语义 json 相等性。但就 django-jsonField 而言,我认为我们真正需要结果正确的可能性很小(可能是 SELECT FALSE 甚至可以解决问题)。
关于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/