create_forms.py 1.62 KB
# -*- coding: utf-8 -*-

from django.db import connection
from django.core.management.base import BaseCommand
from django.db.transaction import atomic

from common.util import uniprint
from export.lexeme_form_query import WHERE_CLAUSES, \
    attr_clauses_combinations, TABLE_FROM_CLAUSES
from dictionary.models import Lexeme, LexemeForm
from tables.models import TableTemplate


class Command(BaseCommand):
    args = 'none'
    help = 'Creates forms for filtering'

    def handle(self, **options):
        create_forms()

VARIANT = '1'


@atomic
def create_forms():
    cursor = connection.cursor()

    cursor.execute('''truncate dictionary_lexemeform''')
    tts = TableTemplate.objects.filter(variant_id=VARIANT).prefetch_related(
        'attributes__values', 'cell_attributes__values')
    for tt in tts:
        uniprint(u'creating forms for: %s' % tt.name)
        attr_clauses, cell_attr_combinations, tt_attr_combinations = \
            attr_clauses_combinations(tt)
        for tt_c in tt_attr_combinations:
            for cell_c in cell_attr_combinations:
                select_query = '''
                    select distinct l.id as lexeme_id,
                        trim(both '+' from
                             cell.prefix||o.rdzen||z.zak||cell.suffix) as form
                    %s where %s and ''' % (TABLE_FROM_CLAUSES, WHERE_CLAUSES)
                select_query += ' and '.join(attr_clauses)
                cursor.execute('''
                    insert into dictionary_lexemeform
                    (lexeme_id, form)
                    (%s)''' % select_query, (tt.id,) + tt_c + cell_c + cell_c)

    print 'commiting to database'