Skip to content

Commit 9a84770

Browse files
committed
add json cursor
1 parent 6b2ba25 commit 9a84770

File tree

4 files changed

+36
-1
lines changed

4 files changed

+36
-1
lines changed

docs/release_notes.rst

+4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
Release Notes
22
=============
33

4+
v3.0.2
5+
------
6+
* Add `json_cursor` to handle django no longer automatically parsing json fields
7+
48
v3.0.1
59
------
610
* Switch to github actions

querybuilder/cursor.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import contextlib
2+
import json
3+
import psycopg2
4+
5+
6+
@contextlib.contextmanager
7+
def json_cursor(django_database_connection):
8+
"""
9+
Cast json fields into their specific types to account for django bugs
10+
https://code.djangoproject.com/ticket/31956
11+
https://code.djangoproject.com/ticket/31973
12+
https://www.psycopg.org/docs/extras.html#psycopg2.extras.register_default_jsonb
13+
"""
14+
with django_database_connection.cursor() as cursor:
15+
psycopg2.extras.register_default_jsonb(conn_or_curs=cursor.cursor, loads=json.loads)
16+
yield cursor

querybuilder/tests/cursor_tests.py

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
from django.db import connection
2+
3+
from querybuilder.cursor import json_cursor
4+
from querybuilder.tests.base import QuerybuilderTestCase
5+
from querybuilder.tests.models import MetricRecord
6+
7+
8+
class JsonCursorTests(QuerybuilderTestCase):
9+
def test_json_cursor(self):
10+
data = {'one': 1, 'two': 2}
11+
MetricRecord.objects.create(data=data)
12+
with json_cursor(connection) as cursor:
13+
cursor.execute(f'select data from {MetricRecord._meta.db_table}')
14+
record = cursor.fetchone()
15+
self.assertEqual(record[0], data)

querybuilder/version.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = '3.0.1'
1+
__version__ = '3.0.2'

0 commit comments

Comments
 (0)