【问题标题】:How do I write an update join postgres query as queryset in Django 1.9?如何在 Django 1.9 中将更新连接 postgres 查询编写为查询集?
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 2021-10-22
    • 2019-12-23
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    相关资源
    最近更新 更多