# coding=utf-8

import re
from django.core.management import BaseCommand
from django.db import transaction
from api.models import WordRel, WordRelResemble, WordRelSynonym

class Command(BaseCommand):
    """
    python manage.py update_20181009_wordrel
    """

    def handle(self, *args, **options):
        wordrel_list = []
        ready_delete = []
        for s in WordRelSynonym.objects.all():
            word = s.word
            words = re.split(u'、+', word)
            if len(words) > 1:
                wordrel_list.extend([
                    WordRelSynonym(
                        wordrel_id=s.wordrel_id,
                        word=w
                    ) for w in words
                ])
                ready_delete.append(s.id)
        with transaction.atomic():
            for wordrel in wordrel_list:
                try:
                    obj, _ = WordRelSynonym.objects.get_or_create(
                        wordrel_id=wordrel.wordrel_id,
                        word=wordrel.word
                    )
                except:
                    pass
            WordRelSynonym.objects.filter(id__in=ready_delete).delete()
        print 'Done!'