如何按创建日期排列搜索结果?

问题描述 投票:3回答:1

我创建了一个搜索栏,但它以旧到新的顺序提供查询,我希望将其更改为新旧。我想先查看我最近的搜索,然后是更旧的搜索。

views.朋友

    search_term=''
    if 'search' in request.GET:
        search_term_extract = request.GET['search']
        search_term = Blog.objects.filter(Q(title__icontains=search_term_extract)|Q(author__username__icontains=search_term_extract))
        paginator = Paginator(search_term, 8)
        page = request.GET.get('page')
        paginator_page = paginator.get_page(page)
        results=search_term.all()['-date_posted']
        message=True
        nav=False

和models.py

class Blog(models.Model):
    title=models.CharField(max_length=100)
    content=models.TextField(blank=True)
    date_posted=models.DateTimeField(default=timezone.now)
    author=models.ForeignKey(User, on_delete=models.CASCADE)
    def __str__(self):
        return self.title
python django
1个回答
0
投票

在查询集上使用.order_by():

search_term = Blog.objects.filter(Q(title__icontains=search_term_extract)|
                             Q(author__username__icontains=search_term_extract)).order_by("-date_posted")
© www.soinside.com 2019 - 2024. All rights reserved.