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