问题
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