我正在尝试使用rest-frameworks ModelViewSet
根据用户的电子邮件地址检索用户。当请求中只包含字母数字字符时,工作正常,但是当包含@
,.
和_
等字符时,它会失败。
我尝试了各种请求,包括:
GET /users/example%40example.com
GET /users/example@example.com
响应返回:
{
"detail": "Not found."
}
请求中的电子邮件地址与数据库中的电子邮件地址完全匹配。
以下是我目前的观点:
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_field = 'email'
答案 0 :(得分:1)
这又是我,我昨天所说的是对的,它不是@
符号,而是导致404错误的.
符号。将您的代码更改为:
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_field = 'email'
lookup_value_regex = '[^/]+'
默认lookup_value_regex为[^/.]+
,here为文档。
查看源代码,您可以在rest_framework/routers.py/SimpleRouter/get_lookup_regex
中看到它:
def get_lookup_regex(self, viewset, lookup_prefix=''):
"""
Given a viewset, return the portion of URL regex that is used
to match against a single instance.
Note that lookup_prefix is not used directly inside REST rest_framework
itself, but is required in order to nicely support nested router
implementations, such as drf-nested-routers.
https://github.com/alanjds/drf-nested-routers
"""
base_regex = '(?P<{lookup_prefix}{lookup_url_kwarg}>{lookup_value})'
# Use `pk` as default field, unset set. Default regex should not
# consume `.json` style suffixes and should break at '/' boundaries.
lookup_field = getattr(viewset, 'lookup_field', 'pk')
lookup_url_kwarg = getattr(viewset, 'lookup_url_kwarg', None) or lookup_field
lookup_value = getattr(viewset, 'lookup_value_regex', '[^/.]+')
return base_regex.format(
lookup_prefix=lookup_prefix,
lookup_url_kwarg=lookup_url_kwarg,
lookup_value=lookup_value
)