您可以使用可写嵌套序列化程序来实现这一点。您需要为其他模型定义序列化程序类,然后日期序列化程序可以如下所示:
class DatesSerializer(serializers.ModelSerializer):
other = OtherSerializer()
class Meta:
model = Dates
fields = ('timestamp', 'feedback', 'myself', 'other')
def validate_other(self, value):
# Run validations for Other model here, either manually or through OtherSerializer's is_valid method. You won't have booking_id in value here though, take that into account when modelling your validation process
def validate_feedback(self, value):
# Run validations specific to feedback field here, if necessary. You can do this for all serializer fields
def validate(self, data):
# Run non-field specific validations for Dates here
def create(self, validated_data):
# At this point, validation for both models are run and passed
# Pop other model data from validated_data first
other_data = validated_data.pop('other')
# Create Dates instance
dates = Dates.objects.create(**validated_data)
# Create Other instance now
Other.objects.create(booking_id=dates, **other_data)
return dates
这里可以使用drf的defaul createmodelmixin,所有嵌套的对象逻辑都在序列化程序中处理。