英文:
How to Add bulk delete by ids in Django Rest Framework
问题
我在Django Rest Framework项目中尝试添加按ID批量删除的功能,但在views.py中遇到了问题。有人知道如何在我的项目中实现这个功能吗?
在我的views.py中的类如下:
class AssignmentViewSet(viewsets.ModelViewSet):
# ... 其他代码 ...
@action(detail=False, methods=['delete'])
def delete_bulk(self, request):
"""通过ids删除多个作业。"""
assignment_ids = request.data.get('ids', [])
self.queryset.filter(user=self.request.user, id__in=assignment_ids).delete()
return Response(status=status.HTTP_204_NO_CONTENT)
我的API负载:
curl -X 'DELETE' \
'http://127.0.0.1:8000/api/assignment/assignment/delete_bulk?ids=8,9' \
-H 'accept: */*' \
-H 'Authorization: Token 1376bfc2439f1347ab16b28fb9e83b83a4336984' \
-H 'X-CSRFTOKEN: x5CfIVresmUTbpG5GlPKAthmZ26WrWv3R5W0etOuhMm5Tbs0skwJMhxDFsT1KxKB'
英文:
I'm trying to add Bulk delete by ids in my Django rest framework project but stucked in views .py anyone knows how to implement this feature in my project?
here is my class in views.py :
class AssignmentViewSet(viewsets.ModelViewSet):
"""View for manage assignment APIs."""
serializer_class = serializers.AssignmentSerializer
queryset = Assgnment.objects.all()
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
def get_queryset(self):
"""Retrieve recipes for authenticated user."""
return self.queryset.filter(user=self.request.user).order_by('-id')
def get_serializer_class(self):
"""Return the serializer class for request."""
if self.action == 'list':
return serializers.AssignmentSerializer
return self.serializer_class
def perform_create(self, serializer):
"""Create a Assignment."""
serializer.save(user=self.request.user)
here is my URLs :
from rest_framework.routers import DefaultRouter
from assignment import views
router = DefaultRouter()
router.register('assignment', views.AssignmentViewSet)
router.register('tags', views.TagViewSet)
app_name = 'assignment'
urlpatterns = [
path('', include(router.urls)),
]
please let me know if you need more details about my project
Update***
I tried this method but not working:
class AssignmentViewSet(viewsets.ModelViewSet):
# ... existing code ...
@action(detail=False, methods=['delete'])
def delete_bulk(self, request):
"""Delete multiple assignments by ids."""
assignment_ids = request.data.get('ids', [])
self.queryset.filter(user=self.request.user, id__in=assignment_ids).delete()
return Response(status=status.HTTP_204_NO_CONTENT)
my API payload:
curl -X 'DELETE' \
'http://127.0.0.1:8000/api/assignment/assignment/delete_bulk?ids=8,9' \
-H 'accept: */*' \
-H 'Authorization: Token 1376bfc2439f1347ab16b28fb9e83b83a4336984' \
-H 'X-CSRFTOKEN: x5CfIVresmUTbpG5GlPKAthmZ26WrWv3R5W0etOuhMm5Tbs0skwJMhxDFsT1KxKB'
答案1
得分: 0
如果需要从query_params获取数据:
data = request.query_params.get("id")
但在你的情况下,更好的方法是在请求体和序列化器中处理。
在你的serializers.py中:
class DeleteAssignmentSerializer(serializers.Serializer):
ids = serializers.ListField(child=serializers.IntegerField())
然后在你的views.py中进行如下操作:
class AssignmentViewSet(viewsets.ModelViewSet):
# ... 现有的代码 ...
@action(detail=False, methods=['delete'])
def delete_bulk(self, request):
"""删除多个任务通过 ids."""
serializer = DeleteAssignmentSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
ids = serializer.data
self.queryset.filter(user=self.request.user, id__in=ids).delete()
return Response(status=status.HTTP_204_NO_CONTENT)
英文:
If you need to get data from query_params:
data = request.query_params.get("id")
But a better approach in your case is to handle in body and serializer.
In your serializers.py:
class DeleteAssignmentSerializer(serializers.Serializer):
ids = serializers.ListField(child=serializers.IntegerField())
And in Your views.py do something like this:
class AssignmentViewSet(viewsets.ModelViewSet):
# ... existing code ...
@action(detail=False, methods=['delete'])
def delete_bulk(self, request):
"""Delete multiple assignments by ids."""
serializer = DeleteAssignmentSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
ids = serializer.data
self.queryset.filter(user=self.request.user, id__in=ids).delete()
return Response(status=status.HTTP_204_NO_CONTENT)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论