我制作了一个序列化程序,在验证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
从嵌套序列化程序创建模型实例的正确方法是什么?
应该使用
serializer.validated_data
,而不是serializer.data
model_obj
保存模型实例,您可以相应地执行操作。 或者可以编写正式文档中提到的create()
或update()
方法反序列化对象:
https://www.django-rest-framework.org/api-guide/serializers/#deserializing-objects
相关问题 更多 >
编程相关推荐