I'm working in Django 1.5.4 and PostgreSQL 9.3, using django-jsonfield for JSONField.
Following query throws db error (could not identify an equality operator for type json):
ModelWithJsonField.objects.annotate(count=Count('field_to_count_by'))
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?
I ran into the same problem and finally (today) implemented a fake operator by running this as admin in the psql console :
(heavily inspired from this thread)
I also referenced your question in the django-jsonfield GitHub issue.
Note that :
I went through the same issue, and then I tried Joachim Jablon's code, and although it seemed to work nicely, it still had issues. I'll get to the point here, the longest version is on my blog.
SELECT '{"a":1,"b":2}'::json = '{"b":2,"a":1}'::json
returnedfalse
, because it is based on the string representation.hash
instead ofbtree
.Then, I created a
json_cmp()
function in PL/V8, that can be used to power the operators necessary for a btree.Here is the complete SQL script
This tends to be a lot slower than simple string comparison, of course, but has the advantage of producing more robust results.
Please note that if you use South for your migrations, you can create an empty migration and execute the SQL from the
forwards()
method. This will automatically install the functions when you migrate your app.My solution uses PL/Python, it parses and re-dumps the json sorting the keys, and then yields the FNV1a hash of the result: https://github.com/ifad/chronomodel/blob/master/sql/json_ops.sql.
I am not using hashtext() because it is for internal use only: http://www.postgresql.org/message-id/24463.1329854466@sss.pgh.pa.us.
It is not a silver bullet, just a crude hack. The real solution is to wait for full support in Postgres.