You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
2.5 KiB
70 lines
2.5 KiB
from rest_framework import serializers
|
|
from .models import VideoCategory, Video, VideoCollection, VideoInCollection
|
|
|
|
|
|
class VideoCategoryListSerializer(serializers.ModelSerializer):
|
|
video_count = serializers.SerializerMethodField()
|
|
|
|
class Meta:
|
|
model = VideoCategory
|
|
fields = ['id', 'title', 'slug', 'video_count']
|
|
|
|
def get_video_count(self, obj):
|
|
return obj.videos.filter(status=True).count()
|
|
|
|
|
|
class VideoListSerializer(serializers.ModelSerializer):
|
|
categories = VideoCategoryListSerializer(many=True, read_only=True)
|
|
|
|
class Meta:
|
|
model = Video
|
|
fields = ['id', 'title', 'slug', 'thumbnail', 'description', 'video_time',
|
|
'view_count', 'categories', 'created_at']
|
|
|
|
|
|
|
|
|
|
|
|
class VideoDetailSerializer(serializers.ModelSerializer):
|
|
related_videos = serializers.SerializerMethodField()
|
|
categories = VideoCategoryListSerializer(many=True, read_only=True)
|
|
|
|
class Meta:
|
|
model = Video
|
|
fields = ['id', 'title', 'slug', 'thumbnail', 'description', 'video_type',
|
|
'video_file', 'video_url', 'video_time', 'view_count',
|
|
'categories', 'created_at', 'related_videos']
|
|
|
|
|
|
def get_related_videos(self, obj):
|
|
# Get all collections that contain this video
|
|
collections = obj.collections.all()
|
|
|
|
if collections.exists():
|
|
# Get all videos from all collections that contain this video
|
|
related_videos = []
|
|
video_ids = set() # To track unique videos
|
|
|
|
for collection in collections:
|
|
# Get all videos in this collection ordered by priority
|
|
videos_in_collection = VideoInCollection.objects.filter(
|
|
video_collection=collection
|
|
).exclude(video=obj).order_by('priority')
|
|
|
|
# Add videos to our list if not already added
|
|
for vic in videos_in_collection:
|
|
if vic.video.id not in video_ids:
|
|
related_videos.append(vic.video)
|
|
video_ids.add(vic.video.id)
|
|
|
|
# Return the related videos using VideoListSerializer
|
|
return VideoListSerializer(related_videos, many=True).data
|
|
|
|
# # If not in a collection, return videos from the same category
|
|
# elif obj.category:
|
|
# related = Video.objects.filter(
|
|
# category=obj.category,
|
|
# status=True
|
|
# ).exclude(id=obj.id)[:5]
|
|
# return VideoListSerializer(related, many=True).data
|
|
return []
|