在Create上更新Django模型

时间:2015-07-10 17:54:32

标签: python django

我正在开发一个简单的预算应用。我想在添加新交易时,我的帐户余额会受到影响。

views.py:

class TransactionList(ListView):
    template_name = 'envelope/transaction_list.html'
    model = Transaction

    def get_context_data(self, **kwargs):
        context = super(TransactionList, self).get_context_data(**kwargs)
        context['account_list'] = Account.objects.all()
        return context

class TransactionCreate(CreateView):
    template_name = 'envelope/transaction_create.html'
    model = Transaction
    fields = '__all__'
    success_url = reverse_lazy('transaction_list')

models.py

class Transaction(models.Model):
    date = models.DateField(default=datetime.today)
    amt = models.DecimalField(decimal_places=2, max_digits=8)
    envelope = models.ForeignKey('Envelope')
    desc = models.CharField(max_length=50)

    def __unicode__(self):
        return u'%s - %s - %s' % (self.date, self.amt, self.desc)

class Account(models.Model):
    name_first = models.CharField(max_length=50)
    name_last = models.CharField(max_length=50)
    amt = models.DecimalField(decimal_places=2, max_digits=8)

如何在创建交易时更改Account.amt字段?

2 个答案:

答案 0 :(得分:1)

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Transaction)
def change_account_amt(sender, instance, created, **kwargs):
    if created:
        # instance is a Transaction created object ...
        acc_obj = Account.objects.get(...)
        acc_obj.amt = ...
        acc_obj.save()

答案 1 :(得分:0)

您可以通过post_save信号轻松完成此操作。它是在save()方法结束时发送的。

from django.db.models.signals import post_save


class Transaction(models.Model):
    ....

class Account(models.Model):
    ... 

# method for updating account amount
def update_account_amount(sender, **kwargs):
    instance = kwargs['instance']
    created = kwargs['created']
    raw = kwargs['raw']
    if created and not raw:
        account = Account.objects.get(...) # get the account object
        account.amt -= instance.amt  # update the amount
        account.save() # save the account object

# register the signal
post_save.connect(update_account_amount, sender=Transaction)