python - Dynamic querys in Django using *args and **kwargs -
i'm trying create search form user can choose few options filter search. i'm getting error:
sortedbyscore() argument after * must sequence, not q
views.py:
def results(request): if request.method != "get": return httpresponse("request method needs get") else: bound_search_form = searchform(request.get) query = request.get['query'] subject = request.get['subject'] grade = request.get['grade'] order_by = request.get['order_by'] kwargs = {} args = () if query: query_word_list = query.split() args = reduce(operator.or_, ((q(title__contains=x) | q(content__contains=x)) x in query_word_list)) if subject != 'all': kwargs["subject"] = subject summaries_list = summary.objects.sortedbyscore(*args, **kwargs) length = len(summaries_list) # pagination paginator = paginator(summaries_list, 4) # page number request page_num = request.get.get('page', 1) # summaries paginator according page number try: summaries = paginator.page(page_num) except(emptypage, invalidpage): summaries = paginator.page(paginator.num_pages) context_dict = { 'sumamount': length, 'summaries': summaries, 'search_form': bound_search_form, } return render(request, 'results.html', context_dict)
code custom manager sortedbyscore:
class summarymanager(models.manager): def sortedbyscore(self, *args, **kwargs): summaries = self.get_queryset().filter(*args, **kwargs) return sorted(summaries, key=lambda summary: summary.get_score(),reverse=true)
args = reduce(operator.or_, ((q(title__contains=x) | q(content__contains=x)) x in query_word_list))
reduce
reduces iterable down single object, after line args
not iterable. reduces args down single q
object or
s of items in query_word_list
together. if want pass using * syntax, you'll need wrap in iterable, i.e. args = (args,)
.
Comments
Post a Comment