如何在Django 1.9中以queryset的形式编写update join postgres查询? 处境
我在Postgres 9.5中有以下疑问如何在Django 1.9中以queryset的形式编写update join postgres查询? 处境,django,postgresql,django-models,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; 这些是我的桌子 wareho
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查询中的所有shelf package_计数?WhPackage.objects.filter(shelf_id=shelf.id)。aggregate(count('shelf'))将返回一个字典,您可以在嵌套查询中检查shelf_计数值并设置为package_计数。更多信息请访问