diff --git a/CHANGELOG.md b/CHANGELOG.md index d9754b6..f6c26af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Current version (in development) + +* Feature: Added `monkey_patch_drf()` utility. + ## v0.7.0 (2023-08-23) This version fixes a bug that affects Django 3.x installations and is recommended for those users. diff --git a/README.md b/README.md index d8da16c..3af8100 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ A drop-in replacement for Django's `AutoField` that gives you "Stripe-style" sel - [Required Parameters](#required-parameters) - [Optional Parameters](#optional-parameters) - [Registering URLs](#registering-urls) + - [Django REST Framework](#django-rest-framework) - [Field Attributes](#field-attributes) - [`.validate_string(strval)`](#validate_stringstrval) - [`.re`](#re) @@ -183,6 +184,18 @@ def user_detail(request, id): ... ``` +### Django REST Framework + +Django REST Framework (DRF) works mostly without issue with `django-spicy-id`. However, an additional step is needed so that DRF treats spicy ID fields as strings, not integers, in serializers. + +You can use the included utility function to monkey patch DRF. It is safe to call this method multiple times. + +```py +from django_spicy_id import monkey_patch_drf + +monkey_patch_drf() +``` + ### Field Attributes The following attributes are available on the field once constructed diff --git a/django_spicy_id/__init__.py b/django_spicy_id/__init__.py index 9d07441..3801048 100644 --- a/django_spicy_id/__init__.py +++ b/django_spicy_id/__init__.py @@ -1,3 +1,4 @@ +from .contrib import monkey_patch_drf from .errors import MalformedSpicyIdError, SpicyIdError from .fields import ( ENCODING_BASE_58, @@ -19,4 +20,5 @@ SpicyIdError, MalformedSpicyIdError, get_url_converter, + monkey_patch_drf, ] diff --git a/django_spicy_id/contrib.py b/django_spicy_id/contrib.py new file mode 100644 index 0000000..591197a --- /dev/null +++ b/django_spicy_id/contrib.py @@ -0,0 +1,13 @@ +from . import fields + + +def monkey_patch_drf(): + """Monkey-patch Django Rest Framework to be aware of our field types. + + Instructs DRF to treat our fields like CharFields. + """ + from rest_framework.fields import CharField + from rest_framework.serializers import ModelSerializer + + for f in (fields.SpicyAutoField, fields.SpicyBigAutoField, fields.SpicySmallAutoField): + ModelSerializer.serializer_field_mapping[f] = CharField