3👍
✅
You can get data from request object directly:
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')
Note if you initiate serializer instance manually in your view, you should pass request to the serializer’s context:
serializer = BookingSerializer(data=data, context={'request': request})
Source:stackexchange.com