import_templates.py 1.45 KB
# -*- coding: utf-8 -*-
import json

from django.core.management.base import BaseCommand

from dictionary.models import LexemeAttribute, LexemeAttributeValue
from tables.models import TableTemplate
from patterns.models import PatternType
from tables.management.commands.import_template import import_template


class Command(BaseCommand):
    help = "Imports templated from JSON."

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

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

ATTRS = dict((attr.name, attr) for attr in LexemeAttribute.objects.all())

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


def import_templates(data):
    TableTemplate.objects.all().delete()
    for tt_data in data:
        tt = import_template(tt_data)
        tt.parts_of_speech = tt_data['parts_of_speech']
        tt.pattern_types = (PATTERN_TYPES[tuple(pt_data)]
                            for pt_data in tt_data['pattern_types'])
        tt.attributes = (ATTRS[attr_name]
                         for attr_name in tt_data['attributes'])
        for av_data in tt_data['attribute_values']:
            tt.attribute_values.add(ATTR_VALS[tuple(av_data)])
        for attr_name in tt_data['cell_attributes']:
            tt.cell_attributes.add(ATTRS[attr_name])
        tt.takes_gender = tt_data['takes_gender']
        tt.save()