Skip to content

Commit

Permalink
feature: add monkey_patch_drf()
Browse files Browse the repository at this point in the history
  • Loading branch information
mik3y committed Dec 25, 2023
1 parent 27612e6 commit 5056c2a
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions django_spicy_id/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from .contrib import monkey_patch_drf
from .errors import MalformedSpicyIdError, SpicyIdError
from .fields import (
ENCODING_BASE_58,
Expand All @@ -19,4 +20,5 @@
SpicyIdError,
MalformedSpicyIdError,
get_url_converter,
monkey_patch_drf,
]
13 changes: 13 additions & 0 deletions django_spicy_id/contrib.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 5056c2a

Please sign in to comment.