0

我有一个 JourneySchedule 模型,其中存储了出发和回程旅程:

class JouaneySchedule(models.Model):
  Owner = models.ForeignKey('Profile', on_delete=models.PROTECT)
  ReturnOf = models.ForeignKey('self', on_delete=models.CASCADE, null=True)
  JourneyDate = models.DateField(null=True)
  JourneyStartTime = models.TimeField()
  IsDepart = models.BooleanField(default=True)
  Fare = models.PositiveIntegerField(null=False, default=0)

出发和回程通过 ReturnOf 自外键连接。

Journey 序列化器是:

class JourneyScheduleSerializer(serializers.ModelSerializer):
Owner = serializers.ReadOnlyField(source='user.id')
ReturnOf = serializers.ReadOnlyField()

class Meta:
    model = JourneySchedule
    fields = (
        'id',
        'Driver',
        'ReturnOf',
        'JourneyDate',
        'JourneyStartTime',
        'IsDepart',
        'Fare'
    )

我已经定义了通勤模型以使用嵌套对象一次保存出发和返回旅程(两者都是旅程的实例)

class CommuteSerializer(serializers.Serializer):
    depart_journey = JourneyScheduleSerializer(required=False)
    return_journey = JourneyScheduleSerializer(required=False)

    class Meta:
        model = JourneySchedule
        fields = ('depart_journey', 'return_journey')

所以我需要先保存depart_journey,然后将id作为ReturnOf字段传递给return_journey。我怎样才能做到这一点?

4

1 回答 1

1

您需要覆盖它create的方法CommuteSerializer,如下所示:

from collections import namedtuple

class CommuteSerializer(serializers.SerializerSerializer):
    depart_journey = JourneyScheduleSerializer(required=False)
    return_journey = JourneyScheduleSerializer(required=False)

    def create(self, validated_data):
        depart_journey = validated_data['depart_journey']
        return_journey = validated_data['return_journey']
        depart_object = JourneySchedule.objects.create(**depart_journey)
        return_object = JourneySchedule.objects.create(ReturnOf=depart_object, **return_journey)
        commute = namedtuple('commute', ['depart_journey', 'return_journey'])
        return commute(depart_journey=depart_journey, return_journey=depart_object) 
于 2018-03-05T12:01:08.637 回答