简体   繁体   English

如何在Django REST中实现方法?

[英]How to implement method in Django REST?

Have the next Django REST question. 有下一个Django REST问题。

I have the view. 我有这个观点。

class MessageViewSet(viewsets.ModelViewSet):
    serializer_class = MessageSerializer
    queryset = Message.objects.filter(isread = False)
    def mark_read():
        queryset = Message.objects.update(isread=True)
        return Response({'read':queryset})

And router in urls.py 和urls.py中的路由器

router = SimpleRouter() router.register(r'api/get_messages', MessageViewSet)

urlpatterns = [
    url(r'^$', MainView.as_view(), name='main'),
    url(r'^', include(router.urls)) ]

Now i have 'get_messages' page which shows all list. 现在我有'get_messages'页面,显示所有列表。

How can i implement a method which would change 'isread' value of model instanse from False to True, when I visit a 'mark_read' page? 当我访问'mark_read'页面时,如何实现一个将模型实例的'isread'值从False更改为True的方法? As you can see, i tried to write method in the class. 如您所见,我试图在课堂上编写方法。 But when i'm trying to call it in urls in this way: 但是当我试图用这种方式在网址中调用它时:

router.register(r'api/mark_read', MessageViewSet.mark_read),

Here comes an error. 这是一个错误。

assert queryset is not None, ' base_name argument not specified, and could ' \\ AssertionError: base_name argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute. assert queryset不是None,' base_name参数未指定,并且未指定'\\ AssertionError: base_name参数,并且无法自动确定视图集中的名称,因为它没有.queryset属性。

Maybe i shouldnt use router, and rewrite view and urls in other way. 也许我不应该使用路由器,并以其他方式重写视图和URL。 If u know how to solve this problem, please answer. 如果你知道如何解决这个问题,请回答。 Thanks. 谢谢。

You can use detail_route or list_route decorators. 您可以使用detail_routelist_route装饰器。

from rest_framework.decorators import list_route

class MessageViewSet(viewsets.ModelViewSet):

    @list_route()
    def mark_read(self, request):
        queryset = Message.objects.update(isread=True)
        return Response({'read':queryset})

With that mark_read method will be available at api/get_messages/mark_read . 使用该mark_read将在api/get_messages/mark_read And you don't need to create separate router, just use one you created for MessageViewSet 而且您不需要创建单独的路由器,只需使用您为MessageViewSet创建的路由器

docs reference docs参考

Since you are using a model viewset you can directly use put or patch rest method to send the desired value for the desired field as the data. 由于您使用的是模型视图集,因此可以直接使用put或patch rest方法将所需字段作为数据发送到所需的字段。 Ideally in rest get should not change model values. 理想情况下,休息时不应更改模型值。 If you really want a different end point put the list_route or detail_route decorator on your mark_read method, and make them a valid call for only a put and/or patch call 如果你真的想要一个不同的终点,请将list_route或detail_route装饰器放在你的mark_read方法上,并使它们成为一个有效的调用,只进行put和/或patch调用

from rest_framework.decorators import list_route

    class MessageViewSet(viewsets.ModelViewSet):

        @list_route(methods=['Patch', 'PUT'])
        def mark_read(self, request):
            queryset = Message.objects.update(isread=True)
            return Response({'read':queryset})

Thanks to @ivan-semochkin and @Shaumux for replies. 感谢@ ivan-semochkin和@Shaumux的回复。 Advices were really helpful. 建议真的很有帮助。

That is my route. 那是我的路线。 I used detail_route instead of list_route. 我使用了detail_route而不是list_route。

@detail_route(methods=['get','put'], url_name='mark_read/')
def mark_read(self, request, pk=None):
    queryset = Message.objects.filter(pk=pk).update(isread=True)
    return Response({'read':queryset})

Now 'isread' value is changing wnen i visit 'mark_read' page. 现在,'isread'值正在改变,我访问'mark_read'页面。 Link: "api/get_messages/pk/mark_read" 链接:“api / get_messages / pk / mark_read”

Does anyone know, is it posslible to make links looking the next way: "api/get_messages" - list, "api/mark_read/pk" - changing isread value. 有谁知道,是否有可能使链接看起来是下一个方式:“api / get_messages” - 列表,“api / mark_read / pk” - 改变读取值。

Is it possible to create something like this? 有可能创造这样的东西吗? "api/mark_read?=pk" “API / mark_read?= PK”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM