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.
86 lines
3.0 KiB
86 lines
3.0 KiB
from rest_framework import serializers
|
|
from ..models.rate import Rate
|
|
|
|
class RateSerializer(serializers.ModelSerializer):
|
|
"""
|
|
Serializer for the Rate model.
|
|
"""
|
|
class Meta:
|
|
model = Rate
|
|
fields = ('id', 'service', 'content_id', 'rate', 'status', 'created_at', 'updated_at')
|
|
read_only_fields = ('id', 'created_at', 'updated_at')
|
|
|
|
def validate(self, data):
|
|
"""
|
|
Validate that the content exists in the specified service.
|
|
"""
|
|
service = data.get('service')
|
|
content_id = data.get('content_id')
|
|
|
|
if not Rate.validate_content_exists(service, content_id):
|
|
raise serializers.ValidationError(f"Content with ID {content_id} does not exist in {service} service.")
|
|
|
|
return data
|
|
|
|
def create(self, validated_data):
|
|
"""
|
|
Create or update a rate.
|
|
If a rate already exists for the user, service, and content_id, update it.
|
|
"""
|
|
user = self.context['request'].user
|
|
service = validated_data.get('service')
|
|
content_id = validated_data.get('content_id')
|
|
|
|
# Try to get an existing rate
|
|
try:
|
|
rate_obj = Rate.objects.get(
|
|
user=user,
|
|
service=service,
|
|
content_id=content_id
|
|
)
|
|
# Update existing rate
|
|
for attr, value in validated_data.items():
|
|
setattr(rate_obj, attr, value)
|
|
rate_obj.save()
|
|
return rate_obj
|
|
except Rate.DoesNotExist:
|
|
# Create new rate
|
|
return Rate.objects.create(user=user, **validated_data)
|
|
|
|
class RateStatusSerializer(serializers.Serializer):
|
|
"""
|
|
Serializer for checking if a user has rated a content and getting the rate value.
|
|
"""
|
|
service = serializers.ChoiceField(choices=Rate.ServiceChoices.choices)
|
|
content_id = serializers.IntegerField(min_value=1)
|
|
|
|
def validate(self, data):
|
|
"""
|
|
Validate that the content exists in the specified service.
|
|
"""
|
|
service = data.get('service')
|
|
content_id = data.get('content_id')
|
|
|
|
if not Rate.validate_content_exists(service, content_id):
|
|
raise serializers.ValidationError(f"Content with ID {content_id} does not exist in {service} service.")
|
|
|
|
return data
|
|
|
|
class AverageRateSerializer(serializers.Serializer):
|
|
"""
|
|
Serializer for getting the average rate of a content.
|
|
"""
|
|
service = serializers.ChoiceField(choices=Rate.ServiceChoices.choices)
|
|
content_id = serializers.IntegerField(min_value=1)
|
|
|
|
def validate(self, data):
|
|
"""
|
|
Validate that the content exists in the specified service.
|
|
"""
|
|
service = data.get('service')
|
|
content_id = data.get('content_id')
|
|
|
|
if not Rate.validate_content_exists(service, content_id):
|
|
raise serializers.ValidationError(f"Content with ID {content_id} does not exist in {service} service.")
|
|
|
|
return data
|