简体   繁体   中英

Multi search query on django 1.3

I'm trying to do implement on my search filters to more than one column but I always get a query error back:

This is my models.py:

class Livro(models.Model):
codigo = models.AutoField(primary_key=True)
nome = models.CharField("Nome", max_length=50)
autor = models.CharField("Autor", max_length=50)
edicao = models.CharField("Edição", max_length=30)
disciplina = models.ForeignKey(Disciplina)
tipo = models.CharField("Tipo", max_length=20, choices = Choices.tipo)
ano = models.CharField("Ano", max_length=30, choices = Choices.ano)
situacao = models.CharField("Situação", max_length=30, choices = Choices.situacao, default = Choices.situacao[0][1], blank = True, null = True)

def __unicode__(self):
    return self.nome

This is my views.py:

def consultar_livro(request):
    if request.method == 'POST':
        nome = request.POST['nome']
        livro =    Livro.objects.filter(nome__icontains=nome).order_by('nome')    
    return render_to_response('consultar_livro.html', locals(),      context_instance = RequestContext(request))

Instead of just the name I also need to use situacao, disciplina, tipo e ano. How should I do it? I've tried both just adding like I did with name and using the Q() function but it doesn't wotk, how to proceed?

Taken from django's builtin admin search here's an example how this could be achieved.

import operator

def get_search_results(request, queryset, search_term):
    """
    Returns a tuple containing a queryset to implement the search,
    and a boolean indicating if the results may contain duplicates.
    """
    # Apply keyword searches.
    def construct_search(field_name):
        if field_name.startswith('^'):
            return "%s__istartswith" % field_name[1:]
        elif field_name.startswith('='):
            return "%s__iexact" % field_name[1:]
        elif field_name.startswith('@'):
            return "%s__search" % field_name[1:]
        else:
            return "%s__icontains" % field_name

    use_distinct = False
    search_fields = get_search_fields(request)
    if search_fields and search_term:
        orm_lookups = [construct_search(str(search_field))
                       for search_field in search_fields]
        for bit in search_term.split():
            or_queries = [models.Q(**{orm_lookup: bit})
                          for orm_lookup in orm_lookups]
            queryset = queryset.filter(reduce(operator.or_, or_queries))
        if not use_distinct:
            for search_spec in orm_lookups:
                if lookup_needs_distinct(queryset.model._meta, search_spec):
                    use_distinct = True
                    break

    return queryset, use_distinct


def get_search_fields(request):
    """
    use double underscores to walk relationsships
    """
    return (
        'nome', 'situacao', 'disciplina__foreign_relation__field',
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM