Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use built-in JSONField #16

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions djsonb/lookups.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import shlex

from django.db.models import Lookup
from django.contrib.postgres.fields import JSONField


class FilterTree:
Expand Down Expand Up @@ -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()
21 changes: 21 additions & 0 deletions tests/djsonb_fields/migrations/0002_auto_20180723_1759.py
Original file line number Diff line number Diff line change
@@ -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(),
),
]
4 changes: 2 additions & 2 deletions tests/djsonb_fields/models.py
Original file line number Diff line number Diff line change
@@ -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()