[Answered ]-How to implement case-insensitive in SlugRelatedField in drf serializers?

1👍

AFAIK, there is no official implementation to make that happen – but, you can create a custom field out of SlugRelatedField(...) something like below,

from rest_framework.relations import SlugRelatedField


class CustomSlugRelatedField(SlugRelatedField):
    def __init__(self, *args, lookup_expr="", **kwargs):
        super().__init__(**kwargs)
        self._slug_field = self.slug_field
        if lookup_expr:
            self.slug_field = f"{self.slug_field}__{lookup_expr}"

    def to_representation(self, obj):
        return getattr(obj, self._slug_field)

and use it as

class MySerializer(ModelSerializer):
    customer = CustomSlugRelatedField(
        queryset=Customer.objects.all(),
        required=False,
        allow_null=True,
        slug_field='name',
        lookup_expr='iexact',
    )
👤JPG

Leave a comment