我有一个嵌套的序列化程序,我想将父序列化数据传递给子。但我不明白我该怎么做。我想做这样的事情:
class BookingSerializer(serializers.ModelSerializer):
use_additional_fields = serializers.BooleanField()
persons = PersonSerializer(many=True)
class PersonSerializer(serializers.ModelSerializer):
def validate_date_of_birth(self, value):
if parent.use_additional_fields and not value:
raise serializers.ValidationError(_('Date of birth is required'))
return value
class Meta:
model = Person
exclude = ('phone', 'date_of_birth')
因此,如果用户在父序列化程序中选择use_additional_fields
,则应该需要子序列化程序中的某些字段
答案 0 :(得分:1)
您可以直接从请求对象获取数据:
class PersonSerializer(serializers.ModelSerializer):
def validate_date_of_birth(self, value):
if self.context['request'].data.get('use_additional_fields') and not value:
raise serializers.ValidationError(_('Date of birth is required'))
return value
class Meta:
model = Person
exclude = ('phone', 'date_of_birth')
请注意,如果您在视图中手动启动序列化程序实例,则应将请求传递给序列化程序context:
serializer = BookingSerializer(data=data, context={'request': request})