autocompletes.py 1.49 KB
from django.http import JsonResponse

from syntax.models_phrase import PhraseType, FixedAttributes, Lemma
from connections.models import Entry
from meanings.models import LexicalUnit

from entries.form_fields.query_managers import RegexQueryManager

lookups = {
    'phrasetype' : (PhraseType, 'text_rep'),
    'lemma'      : (Entry, 'name'),
    'lex_lemma'  : (Lemma, 'name'),
    'fixed'      : (FixedAttributes, 'text'),
    'lu'         : (LexicalUnit,  'text_rep')
}

def autocomplete(request):
    if request.method == 'GET':
        what, text = request.GET['what'], request.GET['text']
        text = '{}.*'.format(text.strip())
        suggestions = []
        print(what)
        if what in lookups:
            model, field = lookups[what]
            qm = RegexQueryManager(lookup=field)
            try:
                queries = qm.make_queries(text, None)
                objects = model.objects.all()
                for query in queries:
                    objects = objects.filter(query).distinct()
                suggestions = sorted(getattr(o, field) for o in objects)
            except Exception as e:
                suggestions = ['brak sugestii (błąd) ' + str(e)]
        else:
            suggestions = ['brak sugestii (nie zdefiniowano)']
        if not suggestions:
            suggestions = ['brak sugestii']
        if len(suggestions) > 10:
            suggestions = suggestions[:10] + ['+ {} sugestii'.format(len(suggestions) - 10)]
        return JsonResponse({'suggestions' : suggestions})