Django and autocomplete, How can I search by First and Last Name?

0

I have the following code that only searches for the name of person, I can not think of how to search also by last name, here I leave the code to try to search by last name but it does not work does not search

views.py

def Buscarpersona(request):
 if request.is_ajax():
    search = request.GET.get('start', '')
    #search2 = request.GET.get('start2', '')
    personas = personalProfile.objects.filter(nombre__A_Paterno__icontains=search)

    results = []
    for pl in personas and apellido:
        place_json ={
        'titulo':pl.titulo,
        'nombre':pl.nombre,
        'A_Paterno':pl.A_Paterno,
        'A_Materno':pl.A_Materno,
        }

        results.append(place_json)
    data = json.dumps(results)
else:
    data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)

Ajax

$(function() {
$("#id_user1").autocomplete({
  minLenght: 4,
  source: function(req, add){
    var search=$("#id_user1").val();
    $.ajax({
      url:"{% url 'user:Buscarpersona' %}",
      async:false,
      dataType:'json',
      type:'GET',
      data:{'start':search},
      success: function(data){

        var suggestions=[];
        $.each(data, function(index, objeto){
          suggestions.push(objeto.titulo+""+ objeto.nombre +" "+ objeto.A_Paterno +" "+ objeto.A_Materno);
        });
        add(suggestions);

      },
      error:function(err){
        alert("no existe el usuario");
      }
    });
  }

});

});

I think I'm making a bad use of __icontains, correct me if I'm wrong

    
asked by Lun 10.12.2018 в 00:12
source

2 answers

1

I think you might be interested in using Q objects

We must import the module:

from django.db.models import Q

And the query could look like this:

personas = personalProfile.objects.filter(Q(nombre__A_Paterno__icontains=search) | Q(apellido__icontains=search))

I do not know if it's exactly what you're looking for, but for many similar searches that you envision, I'm using Q objects. I hope it's helpful.

    
answered by 10.12.2018 / 09:22
source
0

For someone who has a similar problem there I leave the part that I modified so that my code works.

Library

from django.db.models import Q

Part of the code views.py

def Buscarpersona(request):

 if request.is_ajax():
    search = request.GET.get('start', '')
    personas = personalProfile.objects.filter(Q(nombre__icontains=search)|Q(A_Paterno__icontains=search))
    results = []
    for pl in personas:
        place_json ={
        'titulo':pl.titulo,
        'nombre':pl.nombre,
        'A_Paterno':pl.A_Paterno,
        'A_Materno':pl.A_Materno,
        }

        results.append(place_json)
    data = json.dumps(results)
else:
    data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
    
answered by 12.12.2018 в 03:33