我正在测试我的第一个Django API的功能
目前我可以使用请求进行GET和POST
我一直试图通过ID
进行删除请求这是我的REST_FRAMEWORK API代码
@api_view(['GET', 'POST', 'Delete'])
def ShopList(request):
if request.method == 'GET':
snippets = Shop.objects.all()
serializer = ShopSerializer(snippets, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = ShopSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
shop = Shop.objects.get(id=id)
shop.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
在request.method =='DELETE'我试过
elif request.method == 'DELETE':
shop = Shop.objects.all()
shop.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
删除所有内容
如何发出可以按给定ID或其他属性删除记录的DELETE请求?
我的直觉在于
shop = Shop.objects.get(id = id)
通过id获取对象,但我的实现可能是错误的。
这是我的请求代码
import requests
import json
url = 'http://127.0.0.1:8000/shop/'
payload = {'Establishment' : 'MacDonalds', 'Address' : '114/5 Albert St.', 'Suburb' : 'Wellington', 'Postcode' : '8218', 'State' : 'No Data', 'Establishment_Type' : 'Home'}
requests.delete(url, data=json.dumps(payload))
上面的请求方法旨在搜索字典中给出的所有类似记录并将其删除。但是,objects.all()似乎删除了所有内容
我的DELETE请求与此SQL函数类似
DELETE FROM SHOP
WHERE id = 12;
非常感谢您的帮助
答案 0 :(得分:0)
将 ID 添加到有效内容并更改为shop = Shop.objects.get(id = request.data.id)