一旦我保存交易(来自管理员),我想更新交易中涉及的人(债权人和借方)的余额值。这是我的模型:
#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()
这是我的想法,但我只在交易发生变化时工作(第一次保存不起作用):
#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)
我是 Django 的新手,对这样做的正确方法感到非常困惑。我很感激这方面的任何帮助。