I am wondering which one is the best to solve, I have a nested serializer like this:
serializers.py:
class PaymentMethodSerializer(serializers.ModelSerializer): data = serializers.JSONField() payment_type = PaymentTypeSerializer(required=False)
Then the view looks something like this:
class PaymentMethodView(APIView): def put(self, request, id): try: payment_method = PaymentMethod.objects.get(id=id) except ObjectDoesNotExist: return Response("No PaymentMethod with that id", status=status.HTTP_404_NOT_FOUND) payment_method_serialized = PaymentMethodSerializer(instance=payment_method, data=request.data) payment_type = request.data.get("payment_type", None) if payment_type: try: payment_method_type = PaymentType.objects.get(id=payment_type) except ObjectDoesNotExist: payment_method_type = None else: payment_method_type = None
is_valid() returns False and this error:
{"payment_type":{"non_field_errors":["Invalid data. Expected a dictionary, but got int."]}}
I understand, I give the pk serializer. However, I don't want to create a new serializer with PrimaryKeyRelatedField instead of nested relationships just for that. How can I get a PaymentType that matches this pk and then add this object to the request.data dictionary so that is_valid doesn't work? Is this the best way to solve this problem?
django django-rest-framework
alejoss
source share