2

I am trying to code an autocomplete for django which would display multiple queryset instead of a single list, an example of another site that have this implementation can be found here: https://www.uala.it/

Now i was able to send in a queryset the objects of two model:

def multi_autocomplete(request):
    if request.is_ajax():
        # In base a cosa sta scrivendo l'utente mostro un set di aziende.
        query = request.GET.get("term", "")
        companies = Company.objects.filter(name__icontains=query)
        treatments = Treatment.objects.filter(name__icontains=query)
        results = []
        for company in companies:
            place_json = company.name
            results.append(place_json)
        for treatment in treatments:
            place_json = treatment.name
            results.append(place_json)
        data = json.dumps(results)
    return HttpResponse(data, "application/json")

As you can see i'm returning the json.dumps with the data from the two models, how can I change the ui to show the values in different columns like in the link i provided?

2 Answers 2

1

You need to merge both list and send it in response

from django.db.models import F

def multi_autocomplete(request):
    if request.is_ajax():
        query = request.GET.get("term", "")
        companies = Company.objects.filter(name__icontains=query).annotate(value=F('name'), label=F('name')).values('id', 'value', 'label')
        treatments = Treatment.objects.filter(name__icontains=query).annotate(value=F('name'), label=F('name')).values('id', 'value', 'label')
        results = list(companies) + list(treatments)
        data = json.dumps(results)
    else:
        data = 'fail'
    return HttpResponse(data, 'application/json')

Your autocomplete handler will look like.

$("#input_element_id").autocomplete({
     source: "{% url 'url name' %}",
     response: function(event, ui) {
        if (!ui.content.length) {
           var noResult = { value: "", label: "No data found" };
           ui.content.push(noResult);
         }
     },
     select: function (e, ui) {
         if (ui.item.value) {
            //do stuff after user selected option from autocomplete   
         }
     }
});

Update

Check this JsFiddle i think this will help.

Sign up to request clarification or add additional context in comments.

3 Comments

The code you provided is working, and is the same result that i've already achieved, that is a single list with elements of both models... however i don't know how to output this result in two different lists.
exactly, like in the link i have provided: www.uala.it, in that site, if you try they display the results in two list: Trattamenti and Saloni. I don't know how to do something like that!
How to create one of the lists filtered on a related model (FK field)?
0

Try to send the result in dictionary format and handle the same in autocomplete ajax response handler,

clist = []
tlist = []

for company in companies:
    clist.append(company.name)
for treatment in treatments:
    tlist.append(treatment)
data = json.dumps({"companies":clist, "treatments":tlist})
return HttpResponse(data, "application/json")

Autocomplete AJAX handling

$("#input_autocomplete").autocomplete({
        source: function(request, response) {

            $.ajax({
                type:"GET",
                cache:false,
                data:{
                    'term': request.term,
                },
                url: "{% url 'treatment-autocomplete' %}",
                success:function(data) {
                    $("#input_autocomplete").removeClass('ui-autocomplete-loading');
                    $('#companyList').empty();
                    $('#treatmentList').empty();
                    $.each(data['companies'], function(i, item) {
                       $('#companyList').append(item);
                    });
                    $.each(data['treatments'], function(i, item) {
                       $('#treatmentList').append(item);
                    });
                }
           });

        },
        error: function(data) {
            $('#input_autocomplete').removeClass('ui-autocomplete-loading');  
        }
         minLength: 1,
        open: function() {},
        close: function() {},
        focus: function(event,ui) {},
        select: function(event, ui) {}

});

3 Comments

What do you mean by "handle the same in autocomplete ajax response handler"? Can you show me some code for clarification? i am not that good with jquery, i actually have this in my html file: $(function() { $("#input_autocomplete").autocomplete({ source: "{% url 'treatment-autocomplete' %}", minLength: 1, }); });
do you want to display as shown in uala.it ?? you search in one autocomplete box and display the output in two other lists .
yes exaclty, however, I am not getting how to change the output in order to show it in two separated lists (in jQuery).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.