88 lines
2.9 KiB
Python
88 lines
2.9 KiB
Python
from rest_framework import serializers
|
|
|
|
from account.models import User
|
|
from recipe.models import Recipe
|
|
from utils.legacy_parser import parse_legacy_news_content
|
|
|
|
|
|
class RecipeSerializer(serializers.Serializer):
|
|
id = serializers.IntegerField()
|
|
title = serializers.CharField(allow_null=True)
|
|
summary = serializers.CharField(allow_null=True, allow_blank=True)
|
|
body = serializers.CharField(allow_null=True)
|
|
locale = serializers.CharField(allow_null=True)
|
|
state = serializers.CharField(allow_null=True)
|
|
slug = serializers.CharField(allow_null=True)
|
|
created_at = serializers.DateTimeField(format='%m-%d-%Y %H:%M:%S')
|
|
page__attachment_suffix_url = serializers.CharField(allow_null=True)
|
|
page__account_id = serializers.IntegerField(allow_null=True)
|
|
|
|
def validate(self, data):
|
|
data.update({
|
|
'old_id': data.pop('id'),
|
|
'title': self.get_title(data),
|
|
'subtitle': self.get_subtitle(data),
|
|
'description': self.get_description(data),
|
|
'state': self.get_state(data),
|
|
'created': data.pop('created_at'),
|
|
'image': self.get_image(data),
|
|
'created_by': self.get_account(data),
|
|
'modified_by': self.get_account(data),
|
|
})
|
|
|
|
data.pop('page__account_id')
|
|
data.pop('page__attachment_suffix_url')
|
|
data.pop('summary')
|
|
data.pop('body')
|
|
data.pop('locale')
|
|
return data
|
|
|
|
def create(self, validated_data):
|
|
obj, _ = Recipe.objects.update_or_create(
|
|
old_id=validated_data['old_id'],
|
|
defaults=validated_data,
|
|
)
|
|
return obj
|
|
|
|
@staticmethod
|
|
def get_title(data):
|
|
if data.get('title') and data.get('locale'):
|
|
return {data['locale']: data['title']}
|
|
return None
|
|
|
|
@staticmethod
|
|
def get_subtitle(data):
|
|
if data.get('summary') and data.get('locale'):
|
|
return {data['locale']: data['summary']}
|
|
return None
|
|
|
|
@staticmethod
|
|
def get_description(data):
|
|
if data.get('body') and data.get('locale'):
|
|
content = parse_legacy_news_content(data['body'])
|
|
return {data['locale']: content}
|
|
return None
|
|
|
|
@staticmethod
|
|
def get_state(data):
|
|
value = data.get('state')
|
|
states = {
|
|
'published': Recipe.PUBLISHED,
|
|
'hidden': Recipe.HIDDEN,
|
|
'published_exclusive': Recipe.PUBLISHED_EXCLUSIVE
|
|
}
|
|
return states.get(value, Recipe.WAITING)
|
|
|
|
@staticmethod
|
|
def get_image(data):
|
|
values = (None, 'default/missing.png')
|
|
if data.get('page__attachment_suffix_url') not in values:
|
|
return data['page__attachment_suffix_url']
|
|
return None
|
|
|
|
@staticmethod
|
|
def get_account(data):
|
|
if data.get('page__account_id'):
|
|
return User.objects.filter(old_id=data['page__account_id']).first()
|
|
return None
|