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}
原文地址:https://www.cnblogs.com/ywhyme/p/10475196.html
时间: 2024-11-04 15:57:47