简体   繁体   English

在 django ORM 中执行子查询、Sum 和 Join

[英]Performing a Subquery, Sum and Join in django ORM

I have 2 django models which aren't linked by ForeignKey due to legacy system .我有 2 个 django 模型,由于遗留系统,它们没有被 ForeignKey 链接

class Parent(model):
    name -> CharField()

class Child(model)
    parent_name -> CharField()
    cost        -> IntegerField()

I want to achieve a left join which gives me all parent columns along with sum of cost column from children.我想实现一个左连接,它为我提供所有父列以及子项的成本列之和。 SQL in postgres translates to postgres 中的 SQL 转换为

select parent.name, sum(child.cost) as cost from parent join child on parent.name = child.parent_name group by parent.name;

Is there any way to achieve this with django ORM有没有办法用 django ORM 来实现这个

I have tried a lot of things but https://code.djangoproject.com/ticket/28296 might be what is blocking.我已经尝试了很多东西,但https://code.djangoproject.com/ticket/28296可能是阻塞的。

Please use a ForeignKey to refer to a parent, not a CharField that joins on the name.请使用ForeignKey来引用父级,而不是加入名称的CharField This will guarantee referential integrity , avoid data duplication and makes it more convenient to query in Django.这样可以保证引用完整性,避免数据重复,更方便Django中的查询。

You thus define the models as:因此,您将模型定义为:

class Parent(models.Model):
    name = models.CharField(max_length=128)

class Child(models.Model):
    parent = models.ForeignKey(
        Parent,
        on_delete=models.CASCADE
    )
    cost = models.IntegerField()

or if the name of the Parent is unique, you can let it refer to the name :或者如果Parentname是唯一的,你可以让它引用name

class Parent(models.Model):
    name = models.CharField(max_length=128, unique=True)

class Child(models.Model):
    parent = models.ForeignKey(
        Parent,
        to_field='name',
        db_column='parent_name',
        on_delete=models.CASCADE
    )
    cost = models.IntegerField()

then you can .annotate(…) [Django-doc] the Parent model with:然后你可以.annotate(…) [Django-doc] Parent model 使用:

from django.db.models import Sum

Parent.objects.annotate(
    cost=Sum('child__cost')
)

the Parent objects that arise from this queryset will have an extra attribute .cost that will contain the sum of the cost s of the Child s that point to that Parent .由该查询集产生的Parent对象将有一个额外的属性.cost ,它将包含指向该ParentChildcost总和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM