序列化时处理时间字段格式输出
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', ...] # 其他字段