Home > front end >  Django - How to update a parent model using a child model?
Django - How to update a parent model using a child model?

Time:02-02

I have a two models something like this:

models.py

class Parent(models.Model):
  id = models.BigAutoField(primary_key=True)
  quantity = models.DecimalField(max_digits=3, decimal_places=0, null=True)

class Child(models.Model):
  parent = models.ForeignKey('Parent', related_name="parent_child", on_delete=models.CASCADE)
  quantity = models.DecimalField(max_digits=3, decimal_places=0, null=True)

If the parent quantity is different from the sum of the child quantities, Updates the parent quantity to the sum of the child quantities.

I tried to get an object whose parent quantity is different from the sum of the child quantities:

parent = Parents.objects.annotate(sum_quantities=Sum('parent_child__quantity')).exclude(quantity=F('sum_quantities'))

It works! But I'm having trouble updating this. Is there a good way?

CodePudding user response:

Yes, you can use the update() method of the queryset to update the parent quantity to the sum of the child quantities:

Parent.objects.annotate(sum_quantities=Sum('parent_child__quantity')).filter(quantity__ne=F('sum_quantities')).update(quantity=F('sum_quantities'))

This will update the quantity field of all the parents whose quantity is different from the sum of quantity fields of their children.

  • Related