Django restframework serializers 设置各种格式

  • 感觉是Minxin撑起了restframework,所以这里就使用Minxin大法
    Minxin
from rest_framework.fields import Field


class MinxinCustomField:
    """
    想要什么格式,您就尽管设置什么格式
    下面右边的格式定义,在rest_framework.fields  Field
    """
    def __init__(self, *args, **kwargs):
        if hasattr(self, 'serializer_field_mapping') and hasattr(self, 'CustomField'):
            custom_fields = [cf for cf in dir(self.CustomField) if not (cf.startswith('__') and cf.endswith('__'))]
            for default_models_field, default_field in self.serializer_field_mapping.items():
                for field in custom_fields:
                    if issubclass(default_field, Field) and field == default_field.__name__:
                        self.serializer_field_mapping.update(
                            {
                                default_models_field: getattr(self.CustomField, field)
                            }
                        )
                        break
        super(__class__, self).__init__(*args, **kwargs)
  • 自定义格式类,时间格式和时区
import pytz
time_format = "%Y-%m-%d %H:%M:%S"

class MyDateTimeField(serializers.DateTimeField):
    def __init__(self, *args, **kwargs):
        super(MyDateTimeField, self).__init__(format=time_format, default_timezone=pytz.utc, *args, **kwargs)
  • 应用场景,添加Minxin类,格式手动绑定配置
class ProjectSerializer(MinxinCustomField, serializers.ModelSerializer):
    class CustomField:
        DateTimeField = MyDateTimeField

    class Meta:
        model = Project
        fields = '__all__'
  • 注意,CustomField的关键字名 和自定义格式,必须是参考如下右边那列
# path: reste_framework.serializers.py  ModelSerializer
serializer_field_mapping = {
        models.AutoField: IntegerField,
        models.BigIntegerField: IntegerField,
        models.BooleanField: BooleanField,
        models.CharField: CharField,
        models.CommaSeparatedIntegerField: CharField,
        models.DateField: DateField,   
        models.DateTimeField: DateTimeField,
        models.DecimalField: DecimalField,
        models.EmailField: EmailField,
        models.Field: ModelField,
        models.FileField: FileField,
        models.FloatField: FloatField,
        models.ImageField: ImageField,
        models.IntegerField: IntegerField,
        models.NullBooleanField: NullBooleanField,
        models.PositiveIntegerField: IntegerField,
        models.PositiveSmallIntegerField: IntegerField,
        models.SlugField: SlugField,
        models.SmallIntegerField: IntegerField,
        models.TextField: CharField,
        models.TimeField: TimeField,
        models.URLField: URLField,
        models.GenericIPAddressField: IPAddressField,
        models.FilePathField: FilePathField,
    }

你可能感兴趣的:(restframework,python,django,Minxin,serializers)