Django Rest framework custom serialize a field

2019-05-26 13:33发布

问题:

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:

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')