Django Rest框架序列化多个到多个字段

时间:2018-05-03 20:59:05

标签: django django-rest-framework django-serializer

我正在尝试序列化一个带有数组的字段的json有效负载,.is_valid()检查返回true但是当我尝试执行KeyError: 'passengers'时我得到serializer.data['passengers']但是其他字段工作正常(例如booking_number和status)。

这是我传递给seralizer的response.data:

{'booking_number': 2839, 'passengers': [{'first_name': 'Jack', 'surname': 'Smith', 'email': 'smith@mail.com', 'phone_number': '1234'}], 'status': 'ON_HOLD'} 

我的封锁者:

class PassengerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Passenger



class FindBus(serializers.ModelSerializer):
    passengers = PassengerSerializer(read_only=True, many=True)

    class Meta:
        model = Booking
        fields = ('booking_number', 'passengers', 'status')

我的模特:

class Passenger(models.Model):
    first_name = models.CharField(max_length=25)                                    
    surname = models.CharField(max_length=25)                                       
    email = models.EmailField()                                                     
    phone_number = models.CharField(max_length=12) 


class Booking(models.Model):
    booking_number = models.IntegerField(unique=True)                                                                                           
    passenger = models.ManyToManyField(Passenger)                                   
    status = models.CharField(max_length=10)                                        
    hold_time = models.DateTimeField()  

非常感谢任何关于如何使这项工作的建议。

顺便说一下,我跟着这个:Django rest framework serializing many to many field

1 个答案:

答案 0 :(得分:4)

如果您需要反序列化字段,则不应使用read_only=True

class FindBus(serializers.ModelSerializer):
    passengers = PassengerSerializer(many=True)
    ...

请注意,这不足以保存m2m关系:如Writable nested serializers中所述,您还需要定义create()和/或update()方法在你的序列化器上:

class FindBus(serializers.ModelSerializer):
    passengers = PassengerSerializer(many=True)
    ...

    def create(self, validated_data):
        ...

    def update(self, validated_data):
        ...

需要create / update的原因是您必须确定您收到的乘客详细信息是否涉及现有对象或是否需要创建。

您可能还需要向fields = ('__all__',)添加PassengerSerializer(或指定您感兴趣的字段):

class PassengerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Passenger
        fields = ('__all__',)