python - 如何在 PostgreSql 上获取查询的最后 n 个项目

标签 python django python-3.x postgresql django-models

问题:

如何在 Database 级别获取查询的最后 750 条记录?

这是我尝试过的:

# Get last 750 applications

apps = MyModel.active_objects.filter(
    **query_params
).order_by('-created_at').values_list('id', flat=True)[:750]

此查询获取命中 query_params 过滤器的所有记录,然后返回最后 750 条记录。所以我想在 database 级别完成这项工作,比如 mongoDb 聚合查询。可能吗?

谢谢。

最佳答案

实际上,Django 并不是这样工作的。限制部分也是在数据库级别完成的。

Django docs - Limiting QuerySets :

Generally, slicing a QuerySet returns a new QuerySet – it doesn’t evaluate the query.

要查看数据库中实际运行的查询,您可以像这样简单地打印查询:

apps = MyModel.active_objects.filter(
           **query_params
       ).order_by('-created_at').values_list('id', flat=True)[:750]
print(apps.query)

结果会是这样的:

SELECT * FROM "app_mymodel" WHERE <...> ORDER BY "app_mymodel"."created_at" DESC LIMIT 750

关于python - 如何在 PostgreSql 上获取查询的最后 n 个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58982017/

相关文章:

python - 使用 Pandas 如何计算数据组?

python - 没有名为 "backport.configparser"的模块

python - 在 grok 上阻止 python 进程的 SIGKILL

python - 属性错误 : module 'django.contrib.postgres.fields' has no attribute 'JSONField'

Kubernetes 部署上的 Django : Best practices for DB Migrations

python - 扩展 django-tables2

python - 预处理机器学习数据

python - 在 python 中出现几个回溯错误

python-3.x - 如何使用 'flask-graphql' 将资源管理器添加到 GraphiQL?

python-3.x - 如何在不出现在统一面板或 alt-tab 中的情况下运行 python tkinter 应用程序