2016-07-12 9 views
4

状況

私はPostgres 9.5で次のクエリを使用しています。Django 1.9でクエリ結合としてupdate join postgresクエリを書くにはどうすればいいですか?

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; 

これらは私のテーブルです。私は、Djangoのモデルを経由して、個々のパッケージ(例えばなどの更新、作成、削除、保存)に変更を加えるたび

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 querysetを使用して実行し、生のクエリとして実行しないでください。

答えて

0

あなたがモデルとその外部キー関係持って考える:またhttps://docs.djangoproject.com/en見

WhShelf.objects.annotate(package_count=WhPackage.objects. 
       filter(shelf_id=shelf.id).aggregate(Count('shelf'))['shelf__count']) 
+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']) 

Alterantivelyを、あなたは、単一のクエリを実行することができます集計の場合は/1.9/topics/db/queries/およびhttps://docs.djangoproject.com/en/1.9/ref/models/querysets/ – dmitryro

+0

この方法では、シェルフのループが原因で複数のクエリが実行されます。 1つのdjangoクエリーですべてのshelf package_countを更新する方法はありますか? –

+0

WhPackage.objects.filter(shelf_id = shelf.id).aggregate(Count( 'shelf'))は、ネストされたクエリ内のshelf__count値をチェックしてpackage_countに設定できる辞書を返します。詳細はhttps://docs.djangoproject.com/en/1.9/topics/db/aggregation/をご覧ください。 – dmitryro

関連する問題