Created
September 22, 2021 23:44
-
-
Save uhbif19/90ca39364d32c653f90ccac6db9e90c7 to your computer and use it in GitHub Desktop.
TimestampField for DRF with proper validation error and drf-spectacular docs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from drf_spectacular.types import OpenApiTypes | |
from drf_spectacular.utils import extend_schema_field | |
@extend_schema_field(OpenApiTypes.INT) | |
class TimestampField(serializers.DateTimeField): | |
def to_internal_value(self, value): | |
try: | |
return datetime.fromtimestamp(int(value), tz=pytz.UTC) | |
except ValueError: | |
raise exceptions.ValidationError( | |
'Wrong datetime format. Use integer timestamp.' | |
) | |
def to_representation(self, value): | |
return int(value.timestamp()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment