Django REST framework

Extensions for using orjson with Django REST framework.

When using these, install django-orjson with its drf extra to ensure Django REST framework compatibility, for example:

$ python -m pip install 'django-orjson[drf]'

Then configure Django REST framework to swap the default JSON renderer and parser with the orjson-based ones, for example:

REST_FRAMEWORK = {
    "DEFAULT_RENDERER_CLASSES": [
        "django_orjson.rest_framework.JSONRenderer",
    ],
    "DEFAULT_PARSER_CLASSES": [
        "django_orjson.rest_framework.JSONParser",
    ],
}
class django_orjson.rest_framework.JSONRenderer[source]

A subclass of rest_framework.renderers.JSONRenderer that serializes response data with orjson.dumps().

The renderer uses orjson’s native serialization path where possible, with django_orjson.default() configured as orjson’s default callable for extra Django type support such as decimal.Decimal and datetime.timedelta. When indentation is requested, it uses orjson’s two-space indentation regardless of the requested indentation width.

Customize orjson’s default and option parameters by subclassing:

import pathlib

import orjson
from django_orjson import default as base_default
from django_orjson.rest_framework import JSONRenderer


class MyJSONRenderer(JSONRenderer):
    option = orjson.OPT_UTC_Z

    @staticmethod
    def default(obj):
        if isinstance(obj, pathlib.Path):
            return str(obj)
        return base_default(obj)
class django_orjson.rest_framework.JSONParser[source]

A subclass of rest_framework.parsers.JSONParser that parses request data with orjson.loads().

Testing

The following test case classes mirror DRF’s test case classes, with django-orjson’s APIClient as client_class and django-orjson’s JSON assertion methods:

class django_orjson.rest_framework.test.APISimpleTestCase(methodName='runTest')[source]
class django_orjson.rest_framework.test.APITransactionTestCase(methodName='runTest')[source]
class django_orjson.rest_framework.test.APITestCase(methodName='runTest')[source]
class django_orjson.rest_framework.test.APILiveServerTestCase(methodName='runTest')[source]

Use them like DRF’s built-in classes:

from django_orjson.rest_framework.test import APITestCase


class MyAPITests(APITestCase):
    def test_create_account(self):
        response = self.client.post(
            "/accounts/",
            {"name": "DabApps"},
            format="json",
        )
        assert response.status_code == 201
class django_orjson.rest_framework.test.APIClient(enforce_csrf_checks=False, **defaults)[source]

A subclass of both django_orjson.test.Client and rest_framework.test.APIClient.