【发布时间】:2021-01-02 04:45:57
【问题描述】:
我正在尝试更改 Django 上过滤搜索查询的顺序。我正在为我的搜索视图使用基于类的 ListView。我能够从搜索中呈现过滤后的查询集,但是如何更改具有相同搜索的相同查询集的顺序并将其呈现在另一个页面上。有点像 twitter 如何按 top 或 new 排序搜索。我尝试制作不同的视图并更改顺序,但我不确定如何将相同的搜索查询转换为新视图。请帮忙!下面是我的代码。
views.py
class search_view(ListView):
model = Post
template_name = 'main/search.html'
context_object_name = 'posts'
paginate_by = 2
# searches through everything using Q import
def get_queryset(self, *args, **kwargs):
q = self.request.GET.get('q')
self.posts = Post.objects.filter(
Q(ticker__icontains=q) |
Q(user__username__icontains=q) |
Q(content__icontains=q) |
Q(tags__name__icontains=q)
).annotate(
upvoted=Exists(Post.upvotes.through.objects.filter(
user_id=self.request.user.id,
post_id=OuterRef('pk')
))).order_by('-date_traded')
return self.posts
模板.html
<a class="btn btn-secondary dropdown-toggle mb-3 ml-2" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Sort
</a>
<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<a class="dropdown-item" href='?q={{ request.GET.q }}'>New</a>
<a class="dropdown-item" href="#">Top</a> <!-- I would like to render the newly sorted results from here-->
</div>
<!-- the get request for the query-->
<form class="form-inline" method="GET" action="{% url 'main:search' %}">
<input class="form-control mt-2 mr-sm-2" type="search" placeholder="Search by ticker/tags" aria-label="Search" name="q">
<button class="btn btn-outline-info mt-2 mr-sm-2" type="submit" value="Search">Search</button>
</form>
【问题讨论】:
标签: python django search django-views django-class-based-views