gault-millau/apps/transfer/serializers/comments.py
2019-11-05 16:45:43 +05:00

85 lines
2.5 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.ModelSerializer):
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()
class Meta:
model = Comment
fields = (
"id",
"comment",
"mark",
"locale",
"account_id",
"establishment_id"
)
def validate(self, data):
data = self.set_old_id(data)
data = self.set_text(data)
data = self.set_mark(data)
data = self.set_establishment(data)
data = self.set_account(data)
data = self.set_country(data)
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}")
def set_text(self, data):
data['text'] = data.pop('comment')
return data
def set_mark(self, data):
if data['mark'] < 0:
data['mark'] = data['mark'] * -1
return data
def set_account(self, data):
try:
data['user'] = User.objects.filter(old_id=data['account_id']).first()
except User.DoesNotExist as e:
raise ValueError(f"User account not found with {data}: {e}")
del(data['account_id'])
return data
def set_establishment(self, data):
try:
data['content_object'] = Establishment.objects.filter(old_id=data['establishment_id']).first()
except Establishment.DoesNotExist as e:
raise ValueError(f"Establishment not found with {data}: {e}")
# print(f"Establishment not found with {data}: {e}")
del(data['establishment_id'])
return data
def set_old_id(self, data):
data['old_id'] = data.pop("id")
return data
def set_country(self, data):
locale = data.pop("locale")
country_code = locale[:locale.index("-")] if len(locale) > 2 else locale
try:
data['country'] = Country.objects.filter(code=country_code).first()
except Country.DoesNotExist as e:
raise ValueError(f"Country not found with {data}: {e}")
return data