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

时间:2019-05-01 03:45:44

标签: django django-rest-framework django-views

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


孔德代码段

# 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/foo@bar.com/ 的身份访问 详细视图 ,则会引发404

1 个答案:

答案 0 :(得分: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