import_templates.py 1.39 KB
import json
from django.core.management.base import BaseCommand
from dictionary.management.commands.import_template import import_template
from dictionary.models import TableTemplate, PatternType, LexemeAttribute, \
    LexemeAttributeValue


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.lexical_class.symbol), 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)
        for pos in tt_data['parts_of_speech']:
            tt.parts_of_speech.add(pos)
        for pt_data in tt_data['pattern_types']:
            tt.pattern_types.add(PATTERN_TYPES[tuple(pt_data)])
        for attr_name in tt_data['attributes']:
            tt.attributes.add(ATTRS[attr_name])
        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()