common.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # coding=utf-8
  2. """
  3. @project: maxkb
  4. @Author:虎
  5. @file: common.py
  6. @date:2024/1/11 18:44
  7. @desc:
  8. """
  9. from drf_spectacular.types import OpenApiTypes
  10. from drf_spectacular.utils import extend_schema_field
  11. from rest_framework import serializers
  12. from django.utils.translation import gettext_lazy as _
  13. class ObjectField(serializers.Field):
  14. def __init__(self, model_type_list, **kwargs):
  15. self.model_type_list = model_type_list
  16. super().__init__(**kwargs)
  17. def to_internal_value(self, data):
  18. for model_type in self.model_type_list:
  19. if isinstance(data, model_type):
  20. return data
  21. self.fail(_('Message type error'), value=data)
  22. def to_representation(self, value):
  23. return value
  24. class InstanceField(serializers.Field):
  25. def __init__(self, model_type, **kwargs):
  26. self.model_type = model_type
  27. super().__init__(**kwargs)
  28. def to_internal_value(self, data):
  29. if not isinstance(data, self.model_type):
  30. self.fail(_('Message type error'), value=data)
  31. return data
  32. def to_representation(self, value):
  33. return value
  34. class FunctionField(serializers.Field):
  35. def to_internal_value(self, data):
  36. if not callable(data):
  37. self.fail(_('not a function'), value=data)
  38. return data
  39. def to_representation(self, value):
  40. return value
  41. @extend_schema_field(OpenApiTypes.BINARY)
  42. class UploadedImageField(serializers.ImageField):
  43. def __init__(self, **kwargs):
  44. super().__init__(**kwargs)
  45. def to_representation(self, value):
  46. return value
  47. class UploadedFileField(serializers.FileField):
  48. def __init__(self, **kwargs):
  49. super().__init__(**kwargs)
  50. def to_representation(self, value):
  51. return value