加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 13:13:10 所属栏目:Python 来源:网络整理
导读:情况 我在Postgres 9.5中有以下查询. update warehouse_shelf set package_count = counter.resultfrom ( select count(id) as result,shelf_id from warehouse_package group by shelf_id) counterwhere counter.shelf_id = warehouse_shelf.id; 这些是我的
情况

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

在Alterantive中,您可以运行单个查询:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读