1

I have 2 models Parent, Child

class Parent(models.Model):
    id = Base64UUIDField(primary_key=True, editable=False)
    cost = models.DateTimeField(default=None, blank=True, null=True)

class Child(models.Model):
    id = Base64UUIDField(primary_key=True, editable=False)
    cost = models.DateTimeField(default=None, blank=True, null=True)
    parent = models.ForeignKey(Parent, related_name= "children", related_query_name= "child")

I need to populate cost column of Parent objects to maximum cost of all children of that parent

I have tried to annotate to a new column new_cost, and its works.

parents.annotate(new_cost=Max('child__cost'))

But I need to populate values to existing column cost. Tried something like this, but not working.

parents.update(cost=Max('child__cost'))

2 Answers2

2

Probably that can be achieved with a Subquery expression:

from django.db.models import OuterRef, Subquery

Parent.objects.update(
    cost=Subquery(Child.objects.filter(
        parent_id=OuterRef('pk')
    ).values('cost').order_by('-cost')[:1])
)

I would however advise to simply use .annotate(…) when you need the largest cost of the related Childs.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
0

Use aggregate againist to annotate

test = parents.aggregate(new_cost=Max('child__cost'))
parents.update(cost=test["new_cost"])
Reza Heydari
  • 1,146
  • 1
  • 6
  • 10