[Answer]-Modify db object field from .py file in django

2👍

Your get_model_b_by_currency is returning a queryset rather than a single instance. Every time you slice a queryset, you get a new instance. Instead, either return an instance from get_model_b_by_currency – for instance by using get() instead of filter() – or slice it once, allocate it to a variable, and modify and save that variable.

-1👍

Create the following function inside ‘modelA’ class:

def save(self, *args, **kwargs):
    amount_to_add = self.amount  # The amount field in model A class
    model_b = utils.get_model_b_by_currency(self.amount)
    model_b[0].total_amount = model_b[0].total_amount + amount_to_add
    model_b[0].save()
    return super(ModelA, self).save(*args, **kwargs)

Leave a comment