How to combine 2 or more querysets in a Django view?
Posted
by Espen Christensen
on Stack Overflow
See other posts from Stack Overflow
or by Espen Christensen
Published on 2009-01-10T19:51:43Z
Indexed on
2010/03/21
18:21 UTC
Read the original article
Hit count: 279
Hi, I am trying to build the search for a Django site I am building, and in the search I am searching in 3 different models. And to get pagination on the search result list I would like to use a generic object_list view to display the results. But to do that i have to merge 3 querysets into one.
How can i do that? Ive tried this:
result_list = []
page_list = Page.objects.filter(Q(title__icontains=cleaned_search_term) | Q(body__icontains=cleaned_search_term))
article_list = Article.objects.filter(Q(title__icontains=cleaned_search_term) | Q(body__icontains=cleaned_search_term) | Q(tags__icontains=cleaned_search_term))
post_list = Post.objects.filter(Q(title__icontains=cleaned_search_term) | Q(body__icontains=cleaned_search_term) | Q(tags__icontains=cleaned_search_term))
for x in page_list:
result_list.append(x)
for x in article_list:
result_list.append(x)
for x in post_list:
result_list.append(x)
return object_list(request, queryset=result_list, template_object_name='result', paginate_by=10, extra_context={'search_term': search_term}, template_name="search/result_list.html")
But this doesnt work I get an error when i try to use that list in the generic view. The list is missing the clone attribute.
Anybody know how i can merge the three lists, page_list, article_list and post_list?
© Stack Overflow or respective owner