class OrderViewSet(viewsets.ViewSet):
def list(self, request):
orders = Order.objects.all()
return Response({
"code": "success",
"orders": orders,
})
def create(self, request):
comment = request.data["comment"]
product_id = request.data["product_id"]
order = Order(comment=comment, product_id=product_id)
order.save()
return Response({
"code": "success",
})
I would like to return error if product_id is not supplied by the user in request body:
"code": "invalid-request",
"details": {
"product_id": {
"type": "required",
"message": "Product id is required",
}
}
Also, there's KeyError if comment isn't supplied, but I don't want to make comment mandatory in request body. How do I set it to '' if its not supplied & still return success? Thanks
CodePudding user response:
You should use serializers to implement both input data validation and saving model. Note that below example use generic serializers.Serializer
, but you probably want to use serializers.ModelSerializer to validate Order
data, since it will also handle creating model.
class OrderSerializer(serializers.Serializer):
product_id = serializers.IntegerField()
comment = serializers.CharField(required=False, default='')
class OrderViewSet(viewsets.ViewSet):
def list(self, request):
orders = Order.objects.all()
return Response({
"code": "success",
"orders": orders,
})
def create(self, request):
serializer = OrderSerializer(data=request.data)
if serializer.is_valid():
order = Order(**serializer.validated_data)
order.save()
return Response({
"code": "success",
})
return Response({
"code": "invalid-request",
"details": {
error: {
"type": serializer.errors[error][0].code,
"message": serializer.errors[error][0]
} for error in serializer.errors}
}, status=400)