M
M
Meekey2018-11-10 21:45:46
Django
Meekey, 2018-11-10 21:45:46

How to change table field data from another one?

Good evening.
The goal is that when the Transfer model was created , sum was subtracted from whom_from and added to whom_to in Bill . As I understand it, this must be done through save (), but, apparently, I did not set it up correctly. What could be the problem?
models.py

class Bill(models.Model):
    title = models.CharField(max_length=100)
    amount = models.DecimalField(max_digits=19, decimal_places=2, validators=[MinValueValidator(0)], default=0)

    def __str__(self):
        return self.title


class Transfer(models.Model):
    whom_from = models.ForeignKey(Bill, on_delete=models.CASCADE, related_name='whom_from')
    whom_to = models.ForeignKey(Bill, on_delete=models.CASCADE, related_name='whom_to')
    sum = models.DecimalField(max_digits=19, decimal_places=2, validators=[MinValueValidator(0)], default=0)

    def save(self, *args, **kwargs):
        self.whom_to.amount = self.whom_to.amount + self.sum
        self.whom_from.amount = self.whom_from.amount - self.sum
        super(Transfer, self).save(*args, **kwargs)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Meekey, 2018-11-10
@Meekey

I decided.

def save(self, *args, **kwargs):
        self.whom_to.amount = self.whom_to.amount + self.sum
        self.whom_from.amount = self.whom_from.amount - self.sum
        self.whom_from.save()
        self.whom_to.save()
        super(Transfer, self).save(*args, **kwargs)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question