如何在Django 1.9中将​​更新连接postgres查询写为queryset?

时间:2016-07-12 04:04:12

标签: 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执行,并避免将其作为原始查询执行。

1 个答案:

答案 0 :(得分:0)

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

 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'])