import_template.py 2.59 KB
# -*- coding: utf-8 -*-
import json
from django.core.management.base import BaseCommand
from dictionary.models import Variant, TableTemplate, TableCell, \
    PatternType, LexemeAttributeValue, TableHeader, ExportCell, Gender
from patterns.models import BaseFormLabel, PatternType


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())

GENDERS = dict((g.symbol, g) for g in Gender.objects.all())

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

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


def get_bfl(data):
    return BFLS[tuple(data['bfl'])]


def import_template(data):
    def add_restrictions(x, x_data):
        x.pattern_types = (PATTERN_TYPES[tuple(pt_data)]
                           for pt_data in x_data['pattern_types'])
        if 'genders' in x_data:
            x.genders = (GENDERS[gender] for gender in x_data['genders'])
        x.attribute_values = (
            ATTR_VALS[tuple(av_data)] for av_data in x_data['attr_vals'])

    variant = Variant.objects.get(id=data['variant'])
    tt, created = TableTemplate.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 = TableCell(
            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=get_bfl(tc_data), prefix=tc_data['prefix'],
            suffix=tc_data['suffix'])
        tc.save()
        add_restrictions(tc, tc_data)
    for h_data in data.get('headers', []):
        th = TableHeader(
            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 = ExportCell(
            table_template=tt,
            base_form_label=get_bfl(ec_data), prefix=ec_data['prefix'],
            suffix=ec_data['suffix'], tag_template=ec_data['tag'])
        ec.save()
        add_restrictions(ec, ec_data)
    return tt