SearchQuerySet的哪个属性与prefetch_related具有相同的功能?

时间:2015-12-03 07:40:08

标签: python django django-haystack searchqueryset

def get_books_by_query_params(context, query, query_parameters):
binding_query = query_parameters['binding_query']
query_parameters['validate']=1
default_query = None
if query:
    default_queries = [
        Q(title__icontains=query),
        Q(isbn_10__contains=query),
        Q(isbn_13__contains=query),
        Q(publishers=Publisher.objects.filter(name=query)),
        Q(institutes=Institute.objects.filter(name=query)),
        Q(authors=Author.objects.filter(name=query)),
        Q(sellers=Seller.objects.filter(name=query))
    ]

    default_query = reduce(operator.or_, default_queries)
    default_query = default_query & binding_query if binding_query is not None else default_query
elif binding_query is not None:
    default_query = binding_query

if default_query is not None and query_parameters['query_parameters'] is not None:
    books = Book.objects.filter(default_query, validate=1, **query_parameters['query_parameters']).distinct()\
        .prefetch_related('authors').prefetch_related('publishers').prefetch_related('sellers').prefetch_related('institutes')
elif query_parameters['query_parameters']:
    books = Book.objects.filter(validate=1,**query_parameters['query_parameters']).distinct()\
        .prefetch_related('authors').prefetch_related('publishers').prefetch_related('sellers').prefetch_related('institutes')
elif default_query:
    books = Book.objects.filter(default_query,validate=1).distinct().prefetch_related('authors').prefetch_related('publishers').prefetch_related('sellers').prefetch_related('institutes')
else:
    books = Book.objects.filter(validate=1).distinct().prefetch_related('authors').prefetch_related('publishers').prefetch_related('sellers').prefetch_related('institutes')

context['books'] = books
return context

如何使用searchqueryset编写以下代码?在这种情况下,searchqueryset中是否有等效的prefetch_related

1 个答案:

答案 0 :(得分:0)

filter_and

  

<强> SearchQuerySet.filter_and(self, **kwargs)

     

通过查找(和包括)某些属性来缩小搜索范围。查询中的连接行为被强制为AND。用过的   主要通过过滤方法。