Skip to content

Instantly share code, notes, and snippets.

@uhbif19
Created September 22, 2021 23:44
Show Gist options
  • Save uhbif19/90ca39364d32c653f90ccac6db9e90c7 to your computer and use it in GitHub Desktop.
Save uhbif19/90ca39364d32c653f90ccac6db9e90c7 to your computer and use it in GitHub Desktop.
TimestampField for DRF with proper validation error and drf-spectacular docs
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