在DRF路由器中更改查找正则表达式

问题描述 投票:1回答:1

我们如何在视图集和路由器中更改lookup_field的查找正则表达式?


Conde Snippet

# serializers.py
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'email', 'is_staff')


# views.py
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    lookup_field = 'email'

如果我们尝试以/api/v1/users/[email protected]/的身份访问详细视图,它就会提高404

django django-rest-framework django-views
1个回答
1
投票

路由器将匹配包含除斜杠和句点字符之外的任何字符的查找值。对于更严格(或宽松)的查找模式,请在视图集上设置lookup_value_regex属性。这是在视图类中设置lookup_value_regex以匹配lookup_field

# views.py
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    lookup_field = 'email'
    lookup_value_regex = '[\w.@]+' # You can set any valid regex here to match anything excepts 'slashes'

资料来源:DRF Routers

© www.soinside.com 2019 - 2024. All rights reserved.