DRF将日期时间转换为时间戳作为响应

时间:2015-12-02 10:35:37

标签: django django-rest-framework

我的模型包含一个日期时间字段,我想在请求时将其转换为时间戳。以下是响应的get处理程序:

def get(self, request, pk):
    journal = Journal.objects.get(pk=pk)
    serializer = LogSerializer(journal)
    return Response(serializer.data)

以下是回复:

{
  ...blah...
  "created": "2015-12-02T08:57:16.881528Z",
}

我试过这个来获取unix时间戳:

from django.utils.dateformat import format

def get(self, request, pk):
    journal = Journal.objects.get(pk=pk)
    journal.created = format(journal.created, 'U') #error, because the LogSerializer expects a datetime object instead of a string
    serializer = LogSerializer(journal)
    return Response(serializer.data)

这是我的序列化器和型号:

class LogSerializer(ModelSerializer):
    class Meta:
        model = Journal


class Journal(Model):
    created = models.DateTimeField(auto_now_add=True)

有没有办法告诉JSONRender执行以下操作:

if fieldName == 'created': 
    data['created'] = convert_to_timestamp(data['created'])

或者我应该只修改字符串化数据:

content = JSONRender(serializer.data)
... find the position of the time string in content and replace it with the timestamp ...

1 个答案:

答案 0 :(得分:3)

您可以使用SerializerMethodField来实现相同目标。

response_created_date = serializers.SerializerMethodField('get_created_date')

def get_created_date(self, obj):
    return convert_to_timestamp(obj.created)

点击here了解详情。