简体   繁体   中英

Which attribute of SearchQuerySet has the same function as prefetch_related?

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?

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.

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