简体   繁体   English

在创建时更新Django模型

[英]Update Django Model on Create

I'm working on a simple budgeting app. 我正在开发一个简单的预算应用程序。 I would like my account balance to be affected any time I add a new transaction. 我希望每次添加新交易时,我的帐户余额都会受到影响。

views.py: 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 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)

How do I change the Account.amt field when a transaction is created? 创建交易后,如何更改Account.amt字段?

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()

You can do that easily via a post_save signal. 您可以通过post_save信号轻松地做到这post_save It is sent at the end of the save() method. 它在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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM