updated music image handling in serializers

This commit is contained in:
Alexander Karpov 2024-01-12 13:18:04 +03:00
parent fb2b611dd8
commit cb7bbbf49f
2 changed files with 23 additions and 0 deletions

View File

@ -1,3 +1,4 @@
from django.db.models import Q
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
@ -65,6 +66,7 @@ class ListSongSerializer(SetUserModelSerializer):
album = serializers.SerializerMethodField(method_name="get_album")
authors = serializers.SerializerMethodField(method_name="get_authors")
liked = serializers.SerializerMethodField(method_name="get_liked")
image_cropped = serializers.SerializerMethodField(method_name="get_image")
@extend_schema_field(serializers.BooleanField)
def get_liked(self, obj):
@ -88,6 +90,25 @@ def get_authors(self, obj):
).data
return None
@extend_schema_field(serializers.ImageField)
def get_image(self, obj):
img = None
if obj.image_cropped:
img = obj.image_cropped
else:
album = Album.objects.cache().get(id=obj.album_id)
if album.image_cropped:
img = album.image_cropped
else:
authors = Author.objects.cache().filter(
Q(songs__id=obj.id) & ~Q(image="")
)
if authors:
img = authors.first().image_cropped
if img:
return self.context["request"].build_absolute_uri(img.url)
return None
class Meta:
model = Song
fields = [

View File

@ -252,6 +252,7 @@ def update_album_info(album: AlbumModel, author_name: str = None) -> None:
save=True,
)
os.remove(image_path)
album.save()
# Update Album Authors from Spotify data if available
if spotify_album_info and "artists" in spotify_album_info:
@ -334,6 +335,7 @@ def update_author_info(author: Author) -> None:
save=True,
)
os.remove(image_path)
author.save()
if generated_name and not Author.objects.filter(slug=generated_name).exists():
if len(generated_name) > 20: