Gallery-Archivist/backend/api/files/serializers.py

32 lines
1.1 KiB
Python

from rest_framework import serializers
from apps.files.models import PostFileModel
class PostFileSerializer(serializers.ModelSerializer):
"""Serializer for PostFileModel."""
class Meta:
model = PostFileModel
fields = ["hash_blake3", "file_type", "file", "thumbnail"]
# Add any other fields you need
def to_representation(self, instance):
"""Customize the representation of the model."""
representation = super().to_representation(instance)
# Add file name from related model
try:
representation["filename"] = instance.name.first().filename
except (AttributeError, IndexError):
representation["filename"] = "Unknown"
# Add URLs for different thumbnail sizes
base_url = f"/api/files/{instance.hash_blake3}/"
thumbnails = {}
for size_key in THUMBNAIL_SIZES:
thumbnails[size_key] = f"{base_url}?t={size_key}"
representation["thumbnails"] = thumbnails
representation["download_url"] = f"{base_url}?d=0"
return representation