简体   繁体   English

将自定义路由添加到 viewsets.ModelViewSet

[英]Add custom route to viewsets.ModelViewSet

In the docs there is the example of methods with custom url: http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers在文档中有带有自定义 url 的方法示例: http : //www.django-rest-framework.org/tutorial/6-viewsets-and-routers

class SnippetViewSet(viewsets.ModelViewSet):
    ...

    @link(renderer_classes=[renderers.StaticHTMLRenderer])
    def highlight(self, request, *args, **kwargs):
        snippet = self.get_object()
        return Response(snippet.highlighted)

This example add following route:此示例添加以下路由:

url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),

It is possible to add an url without pk param, like this?可以像这样添加没有 pk 参数的网址吗?

r'^snippets/highlight/$'

The ViewSets docs mention using action decorator: ViewSets 文档提到使用action装饰器:

from rest_framework.decorators import action


class SnippetViewSet(viewsets.ModelViewSet):
    ...

    @action(detail=False, methods=['GET'], name='Get Highlight')
    def highlight(self, request, *args, **kwargs):
        queryset = models.Highlight.objects.all()

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

Then just update your queryset to do whatever it needs to do.然后只需更新您的查询集以执行它需要执行的任何操作。

The advantage of doing it this way is that your serialisation is preserved.这样做的好处是可以保留您的序列化。

If your urls.py looks like this:如果您的urls.py如下所示:

from django.contrib import admin
from django.urls import path, include

from rest_framework import routers
from snippets import viewsets

router = routers.DefaultRouter()
router.register('snippets', viewsets.SnippetViewSet)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('snippets/', include(router.urls)),
]

Then it is reachable via http://localhost:8000/snippets/highlights然后它可以通过http://localhost:8000/snippets/highlights

To see usage for a POST , or how to change routing, see docs for routers .要查看POST用法或如何更改路由,请参阅 路由器文档

Yes, you can do that.是的,你可以这样做。 Just add your method in the viewset with the list_route decorator.只需使用list_route装饰器在视图集中添加您的方法。

from rest_framework.decorators import list_route  

class SnippetViewSet(viewsets.ModelViewSet):
    ...

    @list_route(renderer_classes=[renderers.StaticHTMLRenderer])
    def highlight(self, request, *args, **kwargs):
        ...

It will add a url without the pk param like :它将添加一个没有pk参数的网址,例如:

r'^snippets/highlight/$'

You can even specify the methods it supports using the methods argument in your decorator.您甚至可以使用装饰器中的methods参数指定它支持的methods

http://www.django-rest-framework.org/api-guide/routers/#usage http://www.django-rest-framework.org/api-guide/routers/#usage

Since this question still turns up on first Google Page, here is up-to-date (for the late march of 2020) snippet (pun intended) to start working on your custom ModelViewSet route for single object:由于这个问题仍然出现在第一个 Google 页面上,这里是最新的(2020 年 3 月下旬)片段(双关语),用于开始处理单个对象的自定义 ModelViewSet 路由:

from rest_framework.decorators import action


class SnippetViewSet(viewsets.ModelViewSet):
    ...

    @action(detail=True, methods=['POST'], name='Attach meta items ids')
    def custom_action(self, request, pk=None):
        """Does something on single item."""
        queryset = Snippet.objects.get(pk=pk)
        serializer = self.get_serializer(queryset, many=False)
        return Response(serializer.data)

Having default routers from the DRF tutorial will allow you to access this route with: http://localhost:8000/snippets/<int:pk>/custom_action/拥有 DRF 教程中的默认路由器将允许您通过以下方式访问此路由: http://localhost:8000/snippets/<int:pk>/custom_action/

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

相关问题 在viewsets.ModelViewSet上获取params验证 - Get params validation on viewsets.ModelViewSet 混淆何时在 Django 中使用 viewsets.Viewset 和 viewsets.ModelViewSet - confusion when to use viewsets.Viewset and viewsets.ModelViewSet in django 如何在 Django REST 框架中覆盖 viewsets.ModelViewSet? - How do I override viewsets.ModelViewSet in Django REST Framework? 如何在DRF viewsets.ModelViewSet中查询相关object - How to query related object in DRF viewsets.ModelViewSet 是否可以在viewset.ModelViewSet的单个list()方法中从多个模型(表)传递查询集? - Is it possible to pass querysets from multiple models(tables) in a single list() method of viewsets.ModelViewSet? 使用 viewsets.ModelViewSet 视图更新 Django rest 框架 model 中的外键 - Update foreign key in Django rest framework model using viewsets.ModelViewSet view 类视图集的自定义装饰器 - custom decorator for class viewsets 自定义视图集中不允许使用 POST 方法 - POST method not allowed in custom viewsets 如何在Viewsets使用的Django模型中添加列的自定义行级处理 - How to add custom row level processing of a column in Django Model that is used by Viewsets 如何使用 Django DRF viewset.Viewsets 添加自定义操作 function? - How to add a custom action function using Django DRF viewset.Viewsets?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM