【问题标题】:Django GroupBy that return a different valueDjango Group By 返回不同的值
【发布时间】:2017-07-15 00:37:48
【问题描述】:

我有一个看起来像这样的模型:

class Company(models.Model):
    id = models.CharField(max_length=20)
    name = models.CharField(max_length=60)

class Department(models.Model):
    id = models.CharField(max_length=20)
    company_id = models.CharField(max_length=20)
    name = models.CharField(max_length=60)

我想对部门进行分组,以便我知道他们在哪个公司,然后返回公司名称:

Database:

    Company                         Department
id         name                 id      company_id  name
C001        aa                  D001      C001      zz
C002        bb                  D002      C002      yy
C003        cc                  D003      C003      xx
                                D004      C001      uu
                                D005      C003      vv

我想知道设置这样的查询的最佳方法,但会返回公司名称:

Department.objects.filter(id=company_id).groupby(company_id)

Return company_name

预期结果:

D001 and D004 is under C001 wherein the name is aa
D002 is under C002 wherein the name is bb
D003 and D005 is under C003 wherein the name is cc

【问题讨论】:

  • Django 没有 group by,你用的是第三方包吗?

标签: python django aggregation


【解决方案1】:

在您的部门模型中使用 ForeignKey 可能会更容易:

company = ForeignKey('Company')

然后执行以下操作:

company = Company.objects.get(id=company_id) 那么你将拥有: company.namecompany.department_set.all()

https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_one/

【讨论】:

    【解决方案2】:

    在您将模型与 ForeignKey 关联后,正如 Pavel 所写,并且您的查询集与您的所有部门有关,您可以在模板中重新组合:

    {% regroup departments by company_id as company_list %}
    

    现在company_list 是一个包含这样组的列表,您只需设置样式:

    [
     {grouper: C001, list: [D001, D004]},
     {grouper: C002, list: [D002]},
     {grouper: C003, list: [D003, D005]}
    ]
    

    【讨论】:

      猜你喜欢
      • 2018-01-30
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-23
      • 1970-01-01
      相关资源
      最近更新 更多