gault-millau/apps/transfer/serializers/comments.py
2019-11-06 14:24:14 +03:00

57 lines
2.0 KiB
Python

from rest_framework import serializers
from comment.models import Comment, User
from establishment.models import Establishment
from location.models import Country
class CommentSerializer(serializers.Serializer):
id = serializers.IntegerField()
comment = serializers.CharField()
mark = serializers.DecimalField(max_digits=4, decimal_places=2)
locale = serializers.CharField()
account_id = serializers.IntegerField()
establishment_id = serializers.CharField()
def validate(self, data):
data.update({
'old_id': data.pop('id'),
'text': data.pop('comment'),
'mark': data['mark'] * -1 if data['mark'] < 0 else data['mark'],
'content_object': self.get_content_object(data),
'user': self.get_account(data),
'country': self.get_country(data),
})
data.pop('establishment_id')
data.pop('account_id')
data.pop('locale')
return data
def create(self, validated_data):
try:
return Comment.objects.create(**validated_data)
except Exception as e:
raise ValueError(f"Error creating comment with {validated_data}: {e}")
@staticmethod
def get_content_object(data):
establishment = Establishment.objects.filter(old_id=data['establishment_id']).first()
if not establishment:
raise ValueError(f"Establishment not found with old_id {data['establishment_id']}: ")
return establishment
@staticmethod
def get_account(data):
user = User.objects.filter(old_id=data['account_id']).first()
if not user:
raise ValueError(f"User account not found with old_id {data['account_id']}")
return user
@staticmethod
def get_country(data):
locale = data['locale']
country_code = locale[:locale.index("-")] if len(locale) > 2 else locale
country = Country.objects.filter(code=country_code).first()
if not country:
raise ValueError(f"Country not found with code {country_code}")
return country