Rest框架序列化多对多字段

Rest框架序列化多对多字段

本文介绍了Django Rest框架序列化多对多字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to serialise a json payload that has a field with an array, the .is_valid() check is returning true but I am getting KeyError: 'passengers' when I try to do this serializer.data['passengers'] but the other fields work fine (such as booking_number and status).

这是我传递给序列化程序的response.data:

This is the response.data I am passing to the seralizer:

{'booking_number': 2839, 'passengers': [{'first_name': 'Jack', 'surname': 'Smith', 'email': '[email protected]', '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()

任何有关如何进行此工作的建议将不胜感激.

Any advise on how to get this working would be greatly appreciated.

顺便说一句,我正在关注以下内容:将多对多序列化的Django rest框架字段

Btw I was following this: Django rest framework serializing many to many field

推荐答案

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

If you need to de-serialize fields, you should not use read_only=True:

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

请注意,这不足以保存m2m关系:如可写的嵌套序列化器,您还需要在序列化器上定义 create()和/或 update()方法:

Note that this won't be enough for saving m2m relationships: as explained in Writable nested serializers, you'll also need to define create() and/or update() methods on your serializer:

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

    def create(self, validated_data):
        ...

    def update(self, validated_data):
        ...

需要 create / update 的原因是,您必须确定接收到的乘客详细信息是引用现有对象还是需要创建.

The reason for the need of the create/update is that you have to decide whether the passenger details that you receive refer to existing objects or need to be created.

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

You might also need to add fields = ('__all__',) (or specify the fields you're interested in) to your PassengerSerializer:

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

这篇关于Django Rest框架序列化多对多字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:08