Django db错误:在尝试使用jsonfield注释模型时,无法识别类型json的等号运算符 [英] Django db error: could not identify an equality operator for type json when trying to annotate a model with jsonfield

查看:830
本文介绍了Django db错误:在尝试使用jsonfield注释模型时,无法识别类型json的等号运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django 1.5.4和PostgreSQL 9.3中使用 django-jsonfield JSONField。

I'm working in Django 1.5.4 and PostgreSQL 9.3, using django-jsonfield for JSONField.

以下查询引发db错误(无法识别json类型的等价运算符):

Following query throws db error (could not identify an equality operator for type json):

ModelWithJsonField.objects.annotate(count=Count('field_to_count_by'))

field_to_count_by 不是JSONField,普通的int字段。

The field_to_count_by is not JSONField, normal int field.

任何想法我如何解决问题,仍然使用注释?

Any ideas how i can solve the issue and still use annotate?

引擎盖后面有什么注释?

What annotate does behind the hood?

推荐答案

我遇到同样的问题,最后(今天)通过在psql控制台中运行管理员来实现一个假的运算符:

I ran into the same problem and finally (today) implemented a fake operator by running this as admin in the psql console :

-- 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);

(非常灵感来自这个线程)

(heavily inspired from this thread)

我也参考了你的问题django-jsonfield GitHub 问题

I also referenced your question in the django-jsonfield GitHub issue.

请注意:


  • 我对这个影响的想法非常有限。也许这不是一个好主意。这些实现是天真的,但它们应该是足够的。或者也许不是。

  • 特别地,等式运算符检查文本相等,而不是语义json相等。但是,就django-jsonField而言,我认为我们真的需要结果是正确的(可能是SELECT FALSE甚至可以做到这一点)。

这篇关于Django db错误:在尝试使用jsonfield注释模型时,无法识别类型json的等号运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆