序列化时处理时间字段格式输出

from rest_framework import serializers  
from datetime import datetime  
  
class CustomDateTimeField(serializers.DateTimeField):  
    def to_representation(self, value):  
        # 转换 value 为所需的日期时间格式  
        if value is not None:  
            value = value.strftime('%Y-%m-%d %H:%M:%S')  
        return value  
  
class MyModelSerializer(serializers.ModelSerializer):  
    create_time = CustomDateTimeField(read_only=True)  
  
    class Meta:  
        model = MyModel  
        fields = ['create_time', ...]  # 其他字段

 

posted @ 2024-03-22 17:02  凯宾斯基  阅读(14)  评论(0编辑  收藏  举报