Which attribute of SearchQuerySet has the same function as prefetch_related?

坚强是说给别人听的谎言 提交于 2019-12-20 06:36:13

问题


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

How to write the following code using searchqueryset? Is there an equivalent of the prefetch_related in the searchqueryset that can be used in this case?


回答1:


There is filter_and:

SearchQuerySet.filter_and(self, **kwargs)

Narrows the search by looking for (and including) certain attributes. Join behavior in the query is forced to be AND. Used primarily by the filter method.



来源:https://stackoverflow.com/questions/34060293/which-attribute-of-searchqueryset-has-the-same-function-as-prefetch-related

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!