Django Rest Framework-序列化后获取模型实例

2024-05-19 14:31:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我制作了一个序列化程序,在验证POST数据之后,我正试图从序列化程序中的booking字段创建一个Booking实例。但是,由于Booking对象有外键,我得到错误:

ValueError: Cannot assign "4": "Booking.activity" must be a "Activity" instance.

以下是我的视图函数:

@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,其中BookingSerializer是模型序列化程序

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

从嵌套序列化程序创建模型实例的正确方法是什么?


Tags: the实例instance程序viewdata序列化customer
2条回答

应该使用serializer.validated_data,而不是serializer.data

model_obj = serializer.save()

model_obj保存模型实例,您可以相应地执行操作。 或者可以编写正式文档中提到的create()update()方法

反序列化对象:

https://www.django-rest-framework.org/api-guide/serializers/#deserializing-objects

相关问题 更多 >