简体   繁体   English

Django 1.3上的多搜索查询

[英]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: 这是我的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: 这是我的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. 我不仅需要使用名称,还需要使用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? 我已经尝试过像添加名称一样添加和使用Q()函数,但是都没有,如何进行?

Taken from django's builtin admin search here's an example how this could be achieved. 从django的内置管理员搜索中获取,这是一个如何实现此目的的示例。

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',
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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