我是django的新手,并尝试使用 views.py 中的PUT更新模型中的某些数据。这就是我所做的。
@api_view(['PUT'])
def check_coupon(request):
global kid_id, code, serializer
try:
code = request.POST['code']
kid_id = request.POST['kid_id']
except KeyError:
x = None
if request.method == 'PUT':
if services.check_coupon(code) == 1:
services.update_coupon(code, kid_id) # this updates the data
serializer = serializers.CouponSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
更新优惠券:
def update_coupon(code, kid_id):
kid = KidUser.objects.get(id=kid_id)
Coupon.objects.filter(code=code).update(kid_id=kid,used=True)
KidUser.objects.filter(id=kid_id).update(user_type='P')
这会创建一个新的优惠券对象,而不是更新现有的优惠券对象。如何更新特定字段。正文中的输入字段是用户ID和代码。
答案 0 :(得分:0)
所做的更改:
1.删除serializer.save()
方法,该方法将创建具有验证数据的新实例
2.更改了执行顺序,以便update_coupon()
仅在输入数据经过验证时才会运行
@api_view(['PUT'])
def check_coupon(request):
global kid_id, code, serializer
try:
code = request.POST['code']
kid_id = request.POST['kid_id']
except KeyError:
x = None
if request.method == 'PUT':
serializer = serializers.CouponSerializer(data=request.data)
if serializer.is_valid():
# updation process will run only if the serialized data is validated
if services.check_coupon(code) == 1:
services.update_coupon(code, kid_id)
return Response(data=serializer.data)
else:
return Response(data={"message": "Serializer validation error"})
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)