I've made a serializer, and I'm trying to create a Booking instance from the booking field in the serializer, after I've validated the POST data. However, because the Booking object has foreign keys, I'm getting the error: 
ValueError: Cannot assign "4": "Booking.activity" must be a "Activity" instance.
Here's my view function:
@api_view(['POST'])
def customer_charge(request):
    serializer = ChargeCustomerRequestSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    # trying to create an instance using the ReturnDict from the serializer
    booking = Booking(**serializer.data['booking'])
    booking.save()
Serializers.py where BookingSerializer is a ModelSerializer
class ChargeCustomerRequestSerializer(serializers.Serializer):
    booking = BookingSerializer()
    customer = serializers.CharField(max_length=255)
class BookingSerializer(serializers.ModelSerializer):
    class Meta:
        model = Booking
        fields = '__all__'
        # I wanted to view the instances with the nested information available
        # but this breaks the serializer validation if it's just given a foreign key
        # depth = 1
What is the correct way to create a model instance from a nested serializer?
model_obj = serializer.save()
model_obj holds the model instance and you can perform actions accordingly.
or you can write create() or update() method mentioned in official doc
Deserializing objects:
https://www.django-rest-framework.org/api-guide/serializers/#deserializing-objects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With