Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
3.3 kB
2
Indexable
Never
class TaleSerializer(serializers.ModelSerializer):
    """
    Сериализатор для создания сказки.
    """

    class Meta:
        fields = ('child', 'character', 'moral')
        model = Tale

    def _format_text(self, text, values):
        formatted_text = {}
        for page_number, page_data in text.items():
            if isinstance(page_data, dict):
                formatted_text[page_number] = {}
                for key, value in page_data.items():
                    if isinstance(value, str):
                        formatted_text[page_number][key] = value.format(**values)
            if isinstance(page_data, str):
                formatted_text[page_number] = page_data.format(**values)
        return formatted_text

    def _create_tale(self, request, child, character, moral, status, tale_default=None, text=None):
        name = f'{child.name} и {character.character_default.kind} по имени {character.name}'
        tale = Tale(
            name=name,
            user=request.user,
            child=child,
            character=character,
            moral=moral,
            child_name=child.name,
            child_url=child.url,
            text=text,
            tale_default=tale_default,
            status=status
        )
        tale.save()
        tale.refresh_from_db()
        return tale

    def create(self, validated_data):
        request = self.context.get('request')
        child = validated_data.get('child')
        character = validated_data.get('character')
        moral = validated_data.get('moral')
        if child.user != request.user or character.user != request.user:
            raise ValidationError('One or more objects not found.')

        tale_default = TaleDefault.objects.filter(
            moral=moral, 
            character=character.character_default,
            gender_of_child=child.sex,
            tale_default__isnull=False,
        ).first()

        if tale_default:
            tale_entry = Tale.objects.filter(user=request.user, tale_default=default).first()
            logger.info(f'{tale_entry = }')
            if not tale_entry:
                logger.info(f'not tale_entry')
                values = {'name': child.name, 'character_name': character.name}
                text_tale = self._format_text(default.text, values)
                return self._create_tale(request, child, character, moral, Tale.DEFAULT, default, text_tale)
            
        try:
            tale = Tale.objects.get(
                Q(text__isnull=True) & ~Q(status=Tale.FAIL) & ~Q(status=Tale.NEW), 
                user=request.user,
            )
            logger.info(f'{tale = } {tale.status = }')
            if tale.status == Tale.IN_PROGRESS:
                return tale
            else:
                tale.name = f'{child.name} и {character.character_default.kind} по имени {character.name}'
                tale.child = child
                tale.character = character
                tale.moral = moral
                tale.child_name = child.name
                tale.child_url = child.url
                tale.save()
        except Tale.DoesNotExist:
            return self._create_tale(request, child, character, moral, Tale.NEW)
        tale.refresh_from_db()
        return tale