0

I got 3 models (simplifying):

class User(models.Model):
...

class PersonalAccount(models.Model):
    user = models.OneToOneField(user)
    balance = MoneyField()   (like float)

class Withdrawal(models.Model):
   date = models.DateField()
   amount = MoneyField()
   client = ForeignKey(User)
   account =ForeignKey(PersonalAccount)

Every time I save the Withdrawal I must do:

client.PersonalAccount.balance = client.PersonalAccount.balance - withdrawal.amount
client.PersonalAccount.save

What signal should I use to do it? pre_save, post_save or init ones? I want to make it easy to debug. It should not save Withdrawal if any of account operations fail. I'm also totally not sure I got relation syntax right so if someone cold clarify on this..

tshepang
  • 12,111
  • 21
  • 91
  • 136
Lord_JABA
  • 2,545
  • 7
  • 31
  • 58

1 Answers1

0

Logically, the amount has to be reduced once its taken out. So, post_save signal sounds appropriate. Technically you could also use pre_save here without any trouble.

However, since these are asynchronous calls and you should be very careful as they misbehave. Say if you perform 50 requests/min (example), you never know which request is completed first (django does not guarantee the order of processing of requests). Here, you need to carefully manage async calls.

Or else you can simply override the save() model method and perform the actions you want..

def save(obj, *args, **kwargs):
    super(ModelClass, self).save(*args, **kwargs)
    # update your persoanl account
    obj.PersonalAccount.save()

This is better than async calls

Surya
  • 4,824
  • 6
  • 38
  • 63