如何在视图集和路由器中为 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
答案 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