gpt4 book ai didi

python - URL 中的 Django Rest 所需参数

转载 作者:太空宇宙 更新时间:2023-11-03 12:04:11 25 4
gpt4 key购买 nike

我正在使用 Django 休息框架。这是我的代码:

urls.py:

urlpatterns = [
url(r'^users/show', UserShow.as_view()),
]

view.py:

class UserShow(ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer

def get_queryset(self):
queryset = User.objects.all()
username = self.request.query_params.get('username', None)
user_id = self.request.query_params.get('user_id', None)
if username is not None:
queryset = queryset.filter(username=username)
if user_id is not None:
queryset = queryset.filter(pk=user_id)
return queryset

我想像这样从 url 中获取值:/users/show?user_id=1/users/show?username=mike

user_idusername 必须是必需的参数。 如何在基于类的 View 中控制它?

如果我使用错误的参数名称发送请求 /users/show?user111name=mike 或简单的 /users/show 类(class)响应 View 我使用 queryset = User.objects.all() 并列出所有用户。我不需要那个。如果所需参数是 None 响应,我需要 404。

我可以通过基于函数的 View 获得所需的结果:

@api_view(['GET'])
def users(request):
if request.method == 'GET':
queryset = User.objects.all()
username = request.GET.get('username', None)
user_id = request.GET.get('user_id', None)

if username is not None:
queryset = queryset.filter(username=username)
elif user_id is not None:
queryset = queryset.filter(pk=user_id)
else:
return Response({"status": "required field not found."},
status=status.HTTP_404_NOT_FOUND)

if not queryset.exists():
return Response({"status": "not found."},
status=status.HTTP_404_NOT_FOUND)

serializer = UserSerializer(queryset, many=True)
return Response(serializer.data)

但是我如何使用基于通用类的 View 来做到这一点?

最佳答案

class UserIdRetrieve(RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer

class UserUsernameRetrieve(UserIdRetrieve):
lookup_field = 'username'

在 url 中:

urlpatterns = [
url(r'^users/(?P<pk>\d+)/', UserIdRetrieve.as_view()),
url(r'^users/by-username/(?P<username>\w+)/', UserUsernameRetrieve.as_view())
]

如果你的 url 结构是必须的,对上面的小改动:

class UserIdRetrieve(RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer

def get_object(self):
queryset = self.filter_queryset(self.get_queryset())

if 'username' in self.request.query_params:
filter_kwargs = {'username': self.request.query_params['username']}
elif 'user_id' in self.request.query_params:
filter_kwargs = {'id': self.request.query_params['user_id']}
else:
raise Http404('Missing required parameters')

obj = get_object_or_404(queryset, **filter_kwargs)

# May raise a permission denied
self.check_object_permissions(self.request, obj)

return obj

在 url 中:

urlpatterns = [
url(r'^users/show', UserRetrieve.as_view())
]

关于python - URL 中的 Django Rest 所需参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37484865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com