Django - How to update a parent model using a child model?
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?
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.
I solved it.
Parent.objects.annotate(
sum_quantities=Sum('parent_child__quantity')).exclude(quantity=F('sum_quantities')).update(
quantity=Subquery(
Parent.objects.filter(parent=OuterRef('id')).annotate(sum_quantities=Sum('parent_child__quantity')).values('sum_quantities')[:1]
)
)
)