简体   繁体   中英

Modify db object field from .py file in django

I have a form that corresponds to Model A available in models.py which has an "amount" field. I also have a Model B which also has a "total_amount" field. When creating a new Model A through it's corresponding form, after form submition I want to save Model A and modify the total_amount field of Model B so it is : ModelB.total_amount += ModelA.amount. I represented this logic through this lines of code :

def form_valid(self, form):
        self.object = form.save(commit=False)
        amount_to_add = form.cleaned_data['amount']
        model_b = utils.get_model_b_by_currency(form.cleaned_data['currency'])
        model_b[0].total_amount = model_b[0].total_amount + amount_to_add
        model_b[0].save()
        self.object.save()
        return super(ModelFormMixin, self).form_valid(form)

The code is executed correctly, Model A is created, but Models B "total_amount" field is not updated with the new value.

Any idea would be very helpful.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM