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.JSONRendererthat serializes response data withorjson.dumps().The renderer uses orjson’s native serialization path where possible, with
django_orjson.default()configured as orjson’sdefaultcallable for extra Django type support such asdecimal.Decimalanddatetime.timedelta. When indentation is requested, it uses orjson’s two-space indentation regardless of the requested indentation width.Customize orjson’s
defaultandoptionparameters 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.JSONParserthat parses request data withorjson.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:
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.Clientandrest_framework.test.APIClient.