Skip to main content
 首页 » 编程设计

python之django 查询集 : how to get items after a particular id in the queryset

2024年09月07日26cmt

我有一个 id 为的帖子列表:

我想根据 publish_date 对所有帖子进行排序,并在一个 id 之后获取所有帖子。

下面给出了在 publish_date 中排序的所有帖子的查询集

articles = Article.objects.all().order_by('-publish_date') 

在此之后如何在给定的帖子 ID 之后获取包含帖子的查询集。

ID 没有按顺序排列。帖子根据 published_date 排序。因此,根据 published_date order,ID 可以是 10、12、5、7、2、32 等。所以如果我想要 id 5 之后的帖子,它应该只返回 id 顺序为 7、2、32 的查询集

请您参考如下方法:

要获取所有 publish_date 大于特定日期的文章,您可以使用 __gt :

article = Articles.objects.get(id=5) 
articles = Articles.objects.filter(publish_date__gt=article.publish_date) 

如果您只需要 ID,则可以使用 values_list()。

ids = articles.values_list('pk', flat=True)