简体   繁体   English

在 django 中对搜索结果进行排序

[英]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"一样,我需要向他们展示所有搜索结果,然后让他根据likesrecent等对它们进行排序。我该怎么做,因为我在显示结果后就丢失了搜索词。

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.

相关问题 使用 Django 模型过滤器根据单词出现对过滤结果进行排序 - Sorting filtered results based on word occurrence using Django Model Filter 在Django中使用Q表达式时查询后无搜索结果 - No Search results after query when using Q Expression in django Django Haystack和Whoosh搜索正常,但SearchQuerySet返回0个结果 - Django Haystack & Whoosh Search Working, But SearchQuerySet Return 0 Results 为什么不对结果进行排序? - Why it is not Sorting the results? Django/PostgreSQL 全文搜索 - 在 AWS RDS PostgreSQL 上使用 SearchVector 与 SearchVectorField 时的不同搜索结果 - Django/PostgreSQL Full Text Search - Different search results when using SearchVector versus SearchVectorField on AWS RDS PostgreSQL 按关键字和组结果对行进行排序 - Sorting lines by keyword and group results 如何从带有ajax的Django模板中的搜索框结果导航到新链接? - How to navigate to a new link from the search box results in Django template with ajax? 基于搜索查询的排序列表 - Sorting list based on Search Query 假设我的主页中有一个搜索框和一个结果页面来显示结果,我如何在另一个视图中显示 django-filter 结果? - How can i show django-filter results in another view, assuming i have a search box in my home page and a results page to display the results? 搜索列表并打印结果 - Search list and print results
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM