Reputation: 1628
Hello everyone i recently made a autocomplete which is based on my database, the problem is i think it requires a bit of improvement. For example: If a user inputs twice the same value twice, the autocomplete also recommends the same values twice, there is also the problem of escalation i am pretty sure this code might be bad for when my application database size increases. Would love some ideas on how to fix those issues or some good alternatives. Here is the autocomplete view
@login_required
def AutocompleteModelo(request):
if 'term' in request.GET:
query=DataDB.objects.filter(modelo__istartswith=request.GET.get('term'))
modelos=list()
for q in query:
modelos.append(q.modelo)
return JsonResponse(modelos, safe=False)
return render(request,'data.insiradado.html')
And here it is the jquery script for the autocomplete.
<script>
$(function () {
$("#modelo").autocomplete({
source: '{% url 'data-AutocompleteModelo' %}',
minLength: 1
});
});
</script>
Btw modelo is the name of the db column, thanks for the help.
Upvotes: 2
Views: 118
Reputation: 5854
We can use distinct
(Django-Docs) to remove duplicates rows from queryset.
And method values_list
(Django-Docs) returns us a Queryset of tuples then we use list()
to convert it to list.
@login_required
def AutocompleteModelo(request):
term = request.GET.get('term')
if term:
modelos = list(DataDB.objects.filter(
modelo__istartswith=request.GET.get('term')
).values_list(
'modelo', flat=True
).order_by("modelo").distinct("modelo"))
return JsonResponse(modelos, safe=False)
return render(request,'data.insiradado.html')
Note:
On PostgreSQL only, you can pass positional arguments (*fields) in order to specify the names of fields to which the DISTINCT should apply. This translates to a SELECT DISTINCT ON SQL query. Here’s the difference. For a normal distinct() call, the database compares each field in each row when determining which rows are distinct. For a distinct() call with specified field names, the database will only compare the specified field names.
Upvotes: 1