2015-10-17 64 views
1

我使用的是路由器& ReadOnlyModelViewset,並嘗試建立一個API服務,使項目的刪除基於項目只有特定的領域,如: http://localhost/delete_post?author=「ABC 「Django的REST框架刪除項目基於字段

我想urls.py和views.py需要更改,有什麼正確的方法來覆蓋路由器和viewModels來實現這一目標?

models.py

class post(models.Model): 
    author = models.CharField(max_length=100) 
    text = models.CharField(max_length=100) 

views.py

class PostViewSet(viewsets.ReadOnlyModelViewSet): 
    queryset = Post.objects.all() 
    serializer_class = PostSerializer 

回答

0

這看起來像一個批量刪除。我會建議通過過濾和自定義列表路線實現它:

import django_filters 
from rest_framework import status 
from rest_framework.response import Response 
from rest_framework.decorators import list_route 


class PostFilterSet(django_filter.FilterSet): 
    class Meta: 
     model = Post 
     fields = (
      'author', 
     ) 

class PostViewSet(viewsets.ReadOnlyModelViewSet): 
    queryset = Post.objects.all() 
    serializer_class = PostSerializer 
    filter_backends = (
     filters.DjangoFilterBackend, 
    ) 
    filter_class = PostFilterSet 

    @list_route(methods=['post']) 
    def delete_post(self, request, *arg, **kwarg): 
     # retrieve the selected items 
     qs = self.filter_queryset(self.get_queryset()) 
     # delete the selected item 
     qs.delete() 
     # return deleted 
     return Response(status=status.HTTP_204_NO_CONTENT) 
在你的路由器

現在,你有,如果你發佈與查詢參數作者=(筆者沒有名稱,其中提供了新的路徑名爲/ delete_post引號),它會刪除滿足過濾器的所有帖子。