Python django rest 框架 - 使用 detail_route 和 detail_list
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30410432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
django rest framework - using detail_route and detail_list
提问by Ofek Agmon
In my code I have a viewset for the User. I want is to allow only Read operations (/users/42and /users/) which the ReadOnlyModelViewSet does just fine.
在我的代码中,我有一个用户的视图集。我想要的是只允许ReadOnlyModelViewSet 做得很好的读取操作(/users/42和/users/)。
In addition, I want to have a /users/registerURL that I can POSTto in order to register a new User.
此外,我想要一个/users/registerURL,我可以POST到该URL以注册新用户。
class UserViewSet(viewsets.ReadOnlyModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
@list_route(methods=['post'])
def register(request):
serializer = UserSerializer(data=request.DATA)
if serializer.is_valid():
user = User.objects.create_user(
username = serializer.init_data['username'],
password = serializer.init_data['password'],
)
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Couple of questions:
几个问题:
Would this be this the right way of doing that?
Is there a specific signaturefor a method if I put it in a list_routeor the detail_routedecorator? because in the detail_route examples its always the same signature for the method: method_name(self, request, pk=None):
这是这样做的正确方法吗?
如果我将方法放在list_route或detail_route装饰器中,是否有特定的方法签名?因为在 detail_route 示例中,它的方法签名始终相同:method_name(self, request, pk=None):
thanks!
谢谢!
采纳答案by Sebastian Wozny
Your code is almost correct, you're just missing the right signature on the register method:
您的代码几乎是正确的,您只是缺少 register 方法上的正确签名:
def register(self, request):
This is the correct signature according to the documentation. Additionally the testssuggest that it's not possible to pass an additional parameter for routing, and that pk will always be passed for a @detail_route
, so you would have to have:
根据文档,这是正确的签名。此外,测试表明不可能为路由传递附加参数,并且 pk 将始终传递给 a @detail_route
,因此您必须具有:
@detail_route
def register(self, request, pk=None):
for detail routes and
详细路线和
@list_route
def register(self, request):
for list routes.
用于列出路线。
However I would suggest you take advantage of the built in ViewSetMixins as ModelViewSet does internally:
但是,我建议您利用内置的ViewSetMixins,就像 ModelViewSet 在内部一样:
from rest_framework import exceptions, mixins
class UserViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.ListModelMixin,
GenericViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
def create(self, request):
serializer = UserSerializer(data=request.DATA)
if serializer.is_valid():
user = User.objects.create_user(
username = serializer.init_data['username'],
password = serializer.init_data['password'],
)
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
For user sign ups in general you can also take a look at django-registration-restframeworkwhich I'm currently making work for my project.
对于一般的用户注册,您还可以查看我目前正在为我的项目工作的django-registration-restframework。
Personally I rely on the ModelViewSet in my projects and make sure only properly authorized users can perform certain actions. To do this you can use model wide permissionsor in combination with django guardianobject specific permissions.
我个人在我的项目中依赖 ModelViewSet 并确保只有经过适当授权的用户才能执行某些操作。为此,您可以使用模型范围的权限或与django Guardian对象特定权限结合使用。
Especially with a REST API you will eventually come to the point that you'd like certain users to perform actions only on certain objects, without having to micromanage every request. Object level permissions can be of great use here.
特别是使用 REST API,您最终会希望某些用户仅对某些对象执行操作,而不必对每个请求进行微观管理。对象级权限在这里很有用。
回答by Gregory
detail_route and detail_list will get deprecated on DRF 3.0 instead use @action:
detail_route 和 detail_list 将在 DRF 3.0 上被弃用,而是使用 @action:
from rest_framework.decorators import action
@action(methods=['POST'], detail=True)
def sale(self):
...
Use detail=True when this method will account for a single instance of the Model represented by that endpoint and False when it needs to represent a Queryset of that model
当此方法将说明由该端点表示的模型的单个实例时使用 detail=True,当它需要表示该模型的查询集时使用 False