【发布时间】:2019-09-12 20:17:39
【问题描述】:
我有一个通用的 api 视图,我想将它用于放置、删除(并最终更新)某个模型的记录,但我对在 Django 中删除记录的最佳实践感到相当困惑。我应该使用内置的删除方法,还是我自己定义?我是否将其作为 GenericAPIView 上的 DELETE 或“销毁”方法处理。我不想只允许任何人删除记录,所以我需要首先验证他们是创建记录的同一用户。在某些帐户中,听起来 Django 允许您仅使用身份验证和 id 来删除记录。如果为 true,如何禁用此行为?
感谢您提供有关这些不同问题的任何代码或指导。
前端.js
const deleteRow = (id) => {
alert(id)
fetch(`${SERVER_URL}/api/v1/requirements/related_files/${id}`, {
method: 'DELETE',
credentials: 'include',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
Authorization: `Token ${token}`,
},
views.py
class CommentsView(GenericAPIView):
authentication_classes = (TokenAuthentication,)
serializer_class = CommentsSerializer
def post(self, request):
request.data['user'] = request.user.id
comment = CommentsSerializer(data=request.data)
if comment.is_valid():
comment.save()
return Response(comment.data, status=status.HTTP_201_CREATED)
return Response(comment.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self,request):
???? what do I do here ????
【问题讨论】:
-
你有没有试过在 DRF 中使用 mixins,django-rest-framework.org/api-guide/generic-views,你可以重写 DestroyModelMixin 的 on_destroy 方法,为所欲为
标签: python django django-models django-rest-framework django-views