I have 2 django models which aren't linked by ForeignKey due to legacy system.
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
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
I have tried a lot of things but https://code.djangoproject.com/ticket/28296 might be what is blocking.
Please use a
ForeignKeyto refer to a parent, not aCharFieldthat joins on the name. This will guarantee referential integrity, avoid data duplication and makes it more convenient to query in Django.You thus define the models as:
or if the
nameof theParentis unique, you can let it refer to thename:then you can
.annotate(…)[Django-doc] theParentmodel with:the
Parentobjects that arise from this queryset will have an extra attribute.costthat will contain the sum of thecosts of theChilds that point to thatParent.