export_template.py 2.58 KB
# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from common.util import json_encode, uniprint
from tables.models import Variant, TableTemplate


class Command(BaseCommand):
    help = "Exports a table template to JSON."

    def handle(self, name, variant, *args, **options):
        tt = TableTemplate.objects.get(
            name=name.decode('utf-8'), variant__id=variant)
        uniprint(json_encode(export_template(tt)))


def export_template(tt):
    data = {'name': tt.name, 'variant': tt.variant.id}
    if tt.variant.type == Variant.TYPE_TABLE:
        data['table_cells'] = []
        data['headers'] = []
    else:
        data['export_cells'] = []
    table_cells = tt.table_cells.select_related(
        'base_form_label__lexical_class').prefetch_related(
        'pattern_types', 'attribute_values')
    export_cells = tt.export_cells.select_related(
        'base_form_label__lexical_class').prefetch_related(
        'pattern_types', 'attribute_values')
    headers = tt.headers.prefetch_related(
        'pattern_types', 'attribute_values')
    table_elements = [('table_cells', tc) for tc in table_cells]
    table_elements += [('export_cells', ec) for ec in export_cells]
    table_elements += [('headers', h) for h in headers]
    for elem_type, elem in table_elements:
        data_row = {
            'pattern_types': list(
                elem.pattern_types.values_list('symbol', 'lexical_class_id')),
            'attr_vals': list(elem.attribute_values.values_list(
                'value', 'attribute__name')),
        }
        if tt.takes_gender:
            data_row['genders'] = list(
                elem.genders.values_list('symbol', flat=True))
        if elem_type in ('table_cells', 'headers'):
            data_row.update({
                'row': elem.row,
                'col': elem.col,
                'rowspan': elem.rowspan,
                'colspan': elem.colspan,
            })
        if elem_type in ('table_cells', 'export_cells'):
            data_row.update({
                'bfl': (elem.base_form_label.symbol,
                        elem.base_form_label.lexical_class.symbol),
                'prefix': elem.prefix,
                'suffix': elem.suffix,
            })
        if elem_type == 'table_cells':
            data_row['index'] = elem.index
        if elem_type == 'export_cells':
            data_row['tag'] = elem.tag_template
        if elem_type == 'headers':
            data_row.update({
                'label': elem.label,
                'css_class': elem.css_class,
            })
        data[elem_type].append(data_row)
    return data