Django Rest framework custom serialize a field

2019-05-26 13:57发布

I just started using Django REST framework and need to customize a DATETIME field to unix epoch (integer) when serializing it

i currently have

/models.py
class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)

/serializers.py
class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = ('created')

When I call snippets through API, i get typical DATETIME in STR format .

How can I change SnippetSerializer to convert to EPOCH. Also, when someone is posting information, it will come back to me in EPOCH, which I would need to convert to DATETIME . Any ideas?

1条回答
小情绪 Triste *
2楼-- · 2019-05-26 14:11

Please see below code it will help you to solve your problem.

#models.py
class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    def convert_to_epoc(self):
        #paste your conversion code here
        return result

#serializers.py
class SnippetSerializer(serializers.ModelSerializer):
    created = serializers.Field(source='convert_to_epoc')
    class Meta:
        model = Snippet
        fields = ('created')
查看更多
登录 后发表回答