python - Django 数据库错误 : could not identify an equality operator for type json when trying to annotate a model with jsonfield

标签 python django orm django-models django-jsonfield

我在 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/

相关文章:

python - 将值附加到序列化器数据

python - 每次有标点符号就将字符串拆分成句子,有标点符号吗?

python - 如何在应用程序的 urls.py 中设置路径以显示 localhost :8000/xxx(with django2. 1.8)

python - Django QueryDict 为空 request.POST 但在 request.GET 中填充

database - 将消费者定义的聚合(例如 SQL 计数)与 'pure' 模型对象结合起来?

python - Django 为 QuerySet 获取可执行的原始 sql

oop - ORM 是一种反模式吗?

Python:使用 UTF-8 编码读取德语/西类牙语 CSV 文件

python - nltk.KneserNeyProbDist 为大多数三元组给出 0.25 的概率分布

python - 在 python 中使用 unicode