I'd like to update the value of balance of people that are involved in a transaction (creditor and debitors) as soon as I save the transaction (from admin). Here's my models:
#models.py
class Person(models.Model):
first_name = models.CharField(max_length = 30)
last_name = models.CharField(max_length = 30)
phone_number = models.CharField(max_length = 30)
email = models.EmailField('e-mail')
balance = models.DecimalField(max_digits = 5, decimal_places = 2)
class Transaction(models.Model):
creditor = models.ForeignKey(Person,related_name = 'creditor')
debtors = models.ManyToManyField(Person, related_name = 'debtors')
value = models.DecimalField(max_digits = 5, decimal_places = 2)
split = models.BooleanField()
date = models.DateField()
Here's what I thought about, but I only works when the transaction is beeing changed (does not work for the first time save):
#admin.py
class PersonAdmin(admin.ModelAdmin):
list_display = ('first_name','last_name','balance')
class TransactionAdmin(admin.ModelAdmin):
list_display = ('creditor','value','date')
list_filter = ('date',)
date_hierarchy = 'date'
ordering = ('-date',)
filter_horizontal = ('debtors',)
def save_model(self,request,obj,form,change):
obj.save()
if obj.split:
split_value = obj.value/(obj.debtors.all().count()+1)
for debtor in obj.debtors.all():
p = Person.objects.get(id = debtor.id)
p.balance = p.balance - split_value
p.save()
p = Person.objects.get(id = obj.creditor.id)
p.balance = p.balance + (obj.debtors.all().count())*split_value
p.save()
admin.site.register(Person,PersonAdmin)
admin.site.register(Transaction,TransactionAdmin)
I'm new to Django and really confused about the proper way of doing this. I'd appreciate any help on this.