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

时间:2019-04-14 13:02:10

标签: python django

我做了一个搜索栏,但它以旧到新的顺序提供了查询,我想将其更改为新到旧的。我想先查看最近的匹配项,然后再查看较旧的匹配项。

views.py

    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

1 个答案:

答案 0 :(得分: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")