import_variant.py 1.91 KB
#-*- coding:utf-8 -*-

from django.core.management.base import BaseCommand
from dictionary.models import TableTemplate, Cell, TableCell, PartOfSpeech, \
    Variant, PatternType, InflectionCharacteristic, BaseFormLabel


class Command(BaseCommand):
    args = '<variant name> <input file name>'
    help = 'Imports variant from text file'

    def handle(self, variant, filename, **options):
        import_variant(variant, open(filename))


def import_variant(variant, input_file):
    TableTemplate.objects.filter(variant__id=variant).delete()
    for line in input_file:
        if line.startswith(variant):
            line = line.strip().decode('utf-8')
            data = line.split('\t')
            _variant, pos, p_type, ic, row, col, rspan, cspan, bfl, tag, pref, suf, \
            index = data
            assert variant == _variant
            # trochę copypasta
            lc = PartOfSpeech.objects.get(symbol=pos).lexical_class
            v, _created = Variant.objects.get_or_create(id=variant)
            tt_data = {
                'variant': v,
                'pattern_type': PatternType.objects.get(symbol=p_type,
                                                        lexical_class=lc),
                'inflection_characteristic': InflectionCharacteristic.objects.get(
                    symbol=ic, part_of_speech__symbol=pos),
            }
            tt, _created = TableTemplate.objects.get_or_create(**tt_data)
            c = Cell()
            c.table_template = tt
            c.base_form_label = BaseFormLabel.objects.get(symbol=bfl)
            c.tag = tag
            c.prefix = pref
            c.suffix = suf
            c.index = int(index)
            c.save()
            if row:
                tc = TableCell()
                tc.cell = c
                tc.row = int(row)
                tc.col = int(col)
                tc.rowspan = int(rspan)
                tc.colspan = int(cspan)
                tc.save()