DRF更新或创建对象

时间:2018-03-27 17:04:04

标签: python django django-rest-framework

在我的应用程序中,每个产品的人必须在表格中只有一个折扣记录。 我有这个视图用于在db中创建新记录..我如何判断具有提交产品ID的对象是否可以在db中更新目标列,否则创建新对象?如果我使用该函数或其他东西,有些人在序列化器中使用def create ???

class DiscountControllAPiView(APIView):
    """
        each product may takes a discount code or percent from owner or site administrator
    """
    def post(self,request):
        serializer = ProductDiscountControllSerializer(data=request.data)
        if(serializer.is_valid()):
            serializer.save()
            return Response(True)
        else:
            return Response(serializer.errors)

相关的血清化剂:

class ProductDiscountControllSerializer(ModelSerializer):
    class Meta:
        model = ProductDiscountControll
        fields = [
            'product',
            'discount',
            'discount_code',
            'discount_code_precent',
        ]

1 个答案:

答案 0 :(得分:0)

试试这个

class DiscountControllAPiView(APIView):
    """
        each product may takes a discount code or percent from owner or site administrator
    """
    def post(self,request):
        id = request.data.get('id', None):
        if not id:
            # perform creation
            serializer = ProductDiscountControllSerializer(data=request.data)
        else:
            # perform updation
            product_discount_controll = ProductDiscountControll.objects.get(id=int(id))
            serializer = ProductDiscountControllSerializer(product_discount_controll, data=request.data)

        if(serializer.is_valid()):
            serializer.save()
            return Response(True)
        else:
            return Response(serializer.errors)

如果请求中存在id,则api将更新,否则将创建新记录