1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

DjangoでGROUP BYを行う方法

Posted at

例)部署毎の目標合計金額を取得する

目標 - target
部署 - section
社員 - user

model.py
class Target(BaseModel):
    """ 目標モデル """
    # 金額
    amount = models.IntegerField()
    # 社員ID
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    # 部署ID
    section = models.ForeignKey(Section, on_delete=models.PROTECT)
group_by.py
# 部署毎の目標合計金額
total_amount_by_section = (
            Target.objects
            .values("section_id")
            .annotate(section_total=Sum("amount"))
            .values("section_id", "section_total")
        )

1度目のvaluesでsection_idにのみ取得項目を絞り込みますが、後続のannotateでamountの合計値を算出してもエラーにはなりません。発行SQLは下記の通り

total_amount.sql
SELECT
	"target"."section_id",
	SUM("target"."amount") AS "section_total"
FROM
	"target"
GROUP BY
	"target"."section_id";

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?