django rest框架-使用detail_route和detail_list [英] django rest framework - using detail_route and detail_list

查看:345
本文介绍了django rest框架-使用detail_route和detail_list的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我具有用户的视图集。
我想要的是只允许ReadOnlyModelViewSet很好的Read操作( / users / 42 / users / )。

In my code I have a viewset for the User. I want is to allow only Read operations (/users/42 and /users/) which the ReadOnlyModelViewSet does just fine.

此外,我想拥有一个 / users / register URL,我可以对其进行 POST 以便注册新用户。

In addition, I want to have a /users/register URL that I can POST to in order to register a new User.

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)

问题对:


  • 这是这样做的正确方法吗?

  • Would this be this the right way of doing that?

是否有特定的签名(如果我将其放置在 list_route detail_route 装饰器中)?因为在detail_route示例中,该方法的签名始终相同:方法名((自身,请求,pk =无):

Is there a specific signature for a method if I put it in a list_route or the detail_route decorator? because in the detail_route examples its always the same signature for the method: method_name(self, request, pk=None):

谢谢!

推荐答案

您的代码几乎正确,您只是在register方法上缺少正确的签名:

Your code is almost correct, you're just missing the right signature on the register method:

def register(self, request):

根据文档,这是正确的签名。 。另外,测试提示不是可以传递用于路由的附加参数,并且pk将始终以 @detail_route 传递,因此您必须:

This is the correct signature according to the documentation. Additionally the tests suggest 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:

@detail_route
def register(self, request, pk=None):

详细路线和

@list_route
def register(self, request):

用于列表路线。

但是我建议您利用内置的 ViewSetMixins就像ModelViewSet在内部一样

However I would suggest you take advantage of the built in ViewSetMixins as ModelViewSet does internally:

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)

一般来说,对于用户注册,您也可以查看 django-registration- [R estframework ,我目前正在为我的项目工作。

For user sign ups in general you can also take a look at django-registration-restframework which I'm currently making work for my project.

我个人依赖于我的项目中的ModelViewSet,并确保只有经过适当授权的用户才能执行某些操作动作。为此,您可以使用模型范围内的权限或与< a href = https://django-guardian.readthedocs.org/en/v1.2/ rel = noreferrer> django监护人对象特定的权限。

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 permissions or in combination with django guardian object specific permissions.

尤其是使用REST API时,最终您会希望某些用户仅对某些对象执行操作,而不必对每个请求进行微管理。对象级权限在这里很有用。

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.

这篇关于django rest框架-使用detail_route和detail_list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆