django 如何在drf序列化器中实现SlugRelatedField的大小写不敏感?

huwehgph  于 2023-05-19  发布在  Go
关注(0)|答案(1)|浏览(176)

我在我的序列化器中使用SlugRelatedField。我想在不区分大小写的基础上验证它,所以我将后缀“__iexact”添加到“slug_field”属性中。验证可以根据我的需要工作(不区分大小写)。

class MySerializer(ModelSerializer):
    customer = serializers.SlugRelatedField(queryset=Customer.objects.all(),
                                            required=False,
                                            allow_null=True,
                                            slug_field='name__iexact')

但是当我尝试访问www.example.com时serializer.data,出现以下错误:
* {AttributeError}'Customer' object has no attribute 'name__iexact'
怎么解决?

e5nqia27

e5nqia271#

AFAIK,没有官方的实现来实现这一点-但是,您可以创建一个自定义字段的SlugRelatedField(...)如下所示,

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)

并将其用作

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

相关问题