[英]sorting search results in django
I'm have a django app with the following model.我有一个带有以下 model 的 django 应用程序。
class Posts(models.Model):
post = models.TextField(max_length=1500)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
likes = models.ManyToManyField(User, related_name="post_likes")
category = models.CharField(max_length=50, default=None)
To allow the users search for a particular blog and then display those objects I have the following view.为了允许用户搜索特定的博客,然后显示这些对象,我有以下视图。
def index(request):
if request.method == "GET":
search = request.GET.get("input")
posts = Posts.objects.filter(category__icontains=f"{search}")
else:
posts = Posts.objects.all()
params = {'blog': posts}
return render(request, 'index.html', params)
In the above view, variable search
contains what user has searched for, that I'm receiving through a form.在上面的视图中,变量
search
包含用户搜索的内容,我通过表单接收到的内容。 But I also want to provide a sort functionality after user has searched for a blog.但我还想在用户搜索博客后提供排序功能。 Like user searches for
"recipes"
, I need to show them all the search results and then let him sort them based on likes
and recent
etc. How do I do it since I'm losing search terms just after displaying the results.就像用户搜索
"recipes"
一样,我需要向他们展示所有搜索结果,然后让他根据likes
和recent
等对它们进行排序。我该怎么做,因为我在显示结果后就丢失了搜索词。
I'm assuming the sort options are also part of the search form so you could also send the chosen sort option as a query parameter to the backend, just as you're doing with the search term:我假设排序选项也是搜索表单的一部分,因此您也可以将选择的排序选项作为查询参数发送到后端,就像您对搜索词所做的那样:
sort = request.GET.get('sort')
# use the sort options to order your queryset as you desire
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.