Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework - Getting a model instance after serialization

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?

like image 681
Juddling Avatar asked Aug 19 '16 17:08

Juddling


1 Answers

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

like image 133
Prasen-ftech Avatar answered Oct 14 '22 17:10

Prasen-ftech