import_template.py 2.56 KB
# -*- coding: utf-8 -*-
import json
from django.core.management.base import BaseCommand
from dictionary.models import Variant, NewTableTemplate, NewTableCell, \
    PatternType, InflectionCharacteristic, LexemeAttributeValue, NewTableHeader, NewExportCell, BaseFormLabel


class Command(BaseCommand):
    help = "Imports a table template from JSON."

    def handle(self, filename, *args, **options):
        import_template(json.load(open(filename)))

PATTERN_TYPES = dict(
    ((pt.symbol, pt.lexical_class.symbol), pt)
    for pt in PatternType.objects.all())

ICS = dict(
    ((ic.symbol, ic.part_of_speech.symbol), ic)
    for ic in InflectionCharacteristic.objects.all())

ATTR_VALS = dict(
    ((av.value, av.attribute.name), av)
    for av in LexemeAttributeValue.objects.all())

BFLS = dict(
    (bfl.symbol, bfl)
    for bfl in BaseFormLabel.objects.all())

def import_template(data):
    def add_restrictions(x, x_data):
        for pt_data in x_data['pattern_types']:
            x.pattern_types.add(PATTERN_TYPES[tuple(pt_data)]) #add
        for ic_data in x_data['ics']:
            x.inflection_characteristics.add(ICS[tuple(ic_data)]) #add
        for av_data in x_data['attr_vals']:
            x.attribute_values.add(ATTR_VALS[tuple(av_data)]) #add

    variant = Variant.objects.get(id=data['variant'])
    tt, created = NewTableTemplate.objects.get_or_create(
        variant=variant, name=data['name'])
    if not created:
        tt.table_cells.all().delete()
        tt.headers.all().delete()
        tt.export_cells.all().delete()
    for tc_data in data.get('table_cells', []):
        tc = NewTableCell(
            table_template=tt,
            row=tc_data['row'], col=tc_data['col'], rowspan=tc_data['rowspan'],
            colspan=tc_data['colspan'], index=tc_data['index'],
            base_form_label=BFLS[tc_data['bfl']], prefix=tc_data['prefix'],
            suffix=tc_data['suffix'])
        tc.save()
        add_restrictions(tc, tc_data)
    for h_data in data.get('headers', []):
        th = NewTableHeader(
            table_template=tt,
            row=h_data['row'], col=h_data['col'], rowspan=h_data['rowspan'],
            colspan=h_data['colspan'], label=h_data['label'],
            css_class=h_data['css_class'])
        th.save()
        add_restrictions(th, h_data)
    for ec_data in data.get('export_cells', []):
        ec = NewExportCell(
            table_template=tt,
            base_form_label=BFLS[ec_data['bfl']], prefix=ec_data['prefix'],
            suffix=ec_data['suffix'], tag_template=ec_data['tag'])
        ec.save()
        add_restrictions(ec, ec_data)