问题描述
我正在尝试更改Django上已过滤搜索查询的顺序。我将基于类的ListView用于搜索视图。我能够通过搜索呈现过滤的查询集,但是如何更改具有相同搜索的相同查询集的顺序并将其呈现在另一页上。有点像推特如何按顶部或新顺序排序搜索。我尝试制作不同的视图并更改顺序,但不确定如何将相同的搜索查询转换到新视图。请帮忙!下面是我的代码。
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
template.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>
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)