DRF lazy Serializer
1 class LazySerializer: 2 def __init__(self, cls_name, **kwargs): 3 self.cls_name = cls_name 4 self.kwargs = kwargs 5 6 class empty: 7 pass 8 9 def __call__(self, instance=None, data=empty, **kwargs) -> serializers.Serializer: 10 return type(self.cls_name, (serializers.Serializer,), self.kwargs)(instance=instance, data=data, **kwargs) 11 12 13 S = LazySerializer("PeopleSerializer", name=serializers.CharField(), age=serializers.IntegerField(min_value=1)) 14 s = S(data={"name": "xiaoming", "age": 18}) 15 s.is_valid() 16 print(s.data) # {'name': 'xiaoming', 'age': 18}