import_template.py
2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# -*- coding: utf-8 -*-
import json
from django.core.management.base import BaseCommand
from dictionary.models import Variant, TableTemplate, TableCell, \
PatternType, LexemeAttributeValue, TableHeader, ExportCell, BaseFormLabel, \
Gender
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):
for pt_data in x_data['pattern_types']:
x.pattern_types.add(PATTERN_TYPES[tuple(pt_data)]) #add
if 'genders' in x_data:
for gender in x_data['genders']:
x.genders.add(GENDERS[gender]) #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 = 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