diff --git a/djsonb/lookups.py b/djsonb/lookups.py index 68c3011..c0c30d5 100755 --- a/djsonb/lookups.py +++ b/djsonb/lookups.py @@ -4,6 +4,7 @@ import shlex from django.db.models import Lookup +from django.contrib.postgres.fields import JSONField class FilterTree: @@ -271,3 +272,22 @@ def as_sql(self, qn, connection): rhs, rhs_params = self.process_rhs(qn, connection) return FilterTree(rhs_params[0], lhs).sql() + + +@JSONField.register_lookup +class JSONLookup(Lookup): + lookup_name = 'jsonb' + + def as_sql(self, qn, connection): + lhs, lhs_params = self.process_lhs(qn, connection) + rhs, rhs_params = self.process_rhs(qn, connection) + + field = lhs + # JSONField formats query values for the database by wrapping them psycopg2's + # JsonAdapter, but we need the raw Python dict so that we can parse the + # query tree. Intercept the query parameter (it'll always be the first + # element in the parameter list, since the jsonb filter only accepts one argument) + # and revert it back to a Python dict for tree parsing. + tree = rhs_params[0].adapted + + return FilterTree(tree, field).sql() diff --git a/tests/djsonb_fields/migrations/0002_auto_20180723_1759.py b/tests/djsonb_fields/migrations/0002_auto_20180723_1759.py new file mode 100644 index 0000000..3d0c93d --- /dev/null +++ b/tests/djsonb_fields/migrations/0002_auto_20180723_1759.py @@ -0,0 +1,21 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.14 on 2018-07-23 17:59 +from __future__ import unicode_literals + +import django.contrib.postgres.fields.jsonb +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('djsonb_fields', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='jsonbmodel', + name='data', + field=django.contrib.postgres.fields.jsonb.JSONField(), + ), + ] diff --git a/tests/djsonb_fields/models.py b/tests/djsonb_fields/models.py index 40a9b25..f3ed9be 100644 --- a/tests/djsonb_fields/models.py +++ b/tests/djsonb_fields/models.py @@ -1,8 +1,8 @@ # -*- coding: utf-8 -*- from django.db import models -from djsonb.fields import JsonBField +from django.contrib.postgres.fields import JSONField class JsonBModel(models.Model): - data = JsonBField() + data = JSONField()