django - 如何在 Django 1.9 中将更新加入 postgres 查询作为查询集编写?

标签 django postgresql django-models

情况

我在 Postgres 9.5 中有以下查询。

update warehouse_shelf
  set package_count = counter.result
from (
    select count(id) as result, shelf_id 
    from warehouse_package 
    group by shelf_id
) counter
where counter.shelf_id = warehouse_shelf.id;

这些是我的表。

warehouse_shelf
+----+------+---------------+
| ID | NAME | PACKAGE_COUNT |
+----+------+---------------+
|  1 | S1   |             3 |
|  2 | S2   |             1 |
|  3 | S3   |             0 |
+----+------+---------------+

warehouse_package
+----+------+---------------+
| ID | NAME | SHELF_ID      |
+----+------+---------------+
|  1 | P1   |             1 |
|  2 | P2   |             1 |
|  3 | P3   |             1 |
|  4 | P4   |             2 |
+----+------+---------------+

问题

每当我通过 Django 模型对单个包进行更改(例如保存、删除、创建、更新等)时,如何执行上面的查询?

如果可能,我想使用 django queryset 执行并避免将其作为原始查询执行。

最佳答案

考虑到您有模型及其外键关系:

 from django.db.models import Count

 shelves = WhShelf.objects.all()     

 for shelf in shelves:
      count = WhPackage.objects.filter(shelf_id=shelf.id).aggregate(Count('shelf'))
      shelf.update(package_count=count[shelf__count'])

或者,您可以运行单个查询:

WhShelf.objects.annotate(package_count=WhPackage.objects.
                filter(shelf_id=shelf.id).aggregate(Count('shelf'))['shelf__count'])

关于django - 如何在 Django 1.9 中将更新加入 postgres 查询作为查询集编写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38319851/

相关文章:

postgresql - 使用 PostgreSQL 9.5 插入几何 LINE 值

python - 我如何使用 sorl-thumbnail? ( Django )

django - 在 Django Shell 中获取模型的所有字段

django - 从 mongodb 迁移到 postgresql

python - 在pipenv中获取虚拟环境的路径

javascript - 在 Pycharm 中,我无法获取 JSON 文件并且无法安装 fetch

django - 在 Tastypie 中序列化 django-mptt 树

asp.net-mvc - Azure 上托管网站的计费方式 (asp.net mvc)

Django:在查询中的 datetime.timedelta 中使用 F 参数

c# - 无法安装 Microsoft Power Bi Postgresql 连接器