【发布时间】:2016-07-12 04:04:12
【问题描述】:
情况
我在 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 执行,并避免将其作为原始查询执行。
【问题讨论】:
标签: django postgresql django-models