我们如何在视图集和路由器中更改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/[email protected]/
的身份访问详细视图,它就会提高404
路由器将匹配包含除斜杠和句点字符之外的任何字符的查找值。对于更严格(或宽松)的查找模式,请在视图集上设置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