autocompletes.py
1.45 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
from django.http import JsonResponse
from syntax.models_phrase import PhraseType, FixedAttributes
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'),
'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})