通过一个序列化程序保存两个相关模型并将第一个 id 作为 django rest 框架中的外键传递给第二个?

Saving two related models via one serializer and passing the first id to the second as a foreign key in django rest framework?

我有一个 JourneySchedule 模型,它存储出发和 return 旅程:

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)

出发和 return 旅程通过 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'
    )

我定义了通勤模型以使用嵌套对象同时保存出发和 return 旅程(两者都是旅程的实例)

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。我怎样才能做到这一点?

你需要为它覆盖 CommuteSerializercreate 方法,像这样:

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)