我正在使用路由器& ReadOnlyModelViewset,并尝试创建一个API服务,该服务允许仅基于项目中的特定字段删除项目,例如: http://localhost/delete_post?author= “ABC”
我猜urls.py和views.py需要更改,覆盖路由器和viewModel的正确方法是什么?
models.py
0-6
views.py
class post(models.Model):
author = models.CharField(max_length=100)
text = models.CharField(max_length=100)
答案 0 :(得分: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的新路由,如果您使用查询param author =(没有引号的作者姓名)发布,它将删除满足过滤器的所有帖子。