【发布时间】:2020-11-24 21:15:37
【问题描述】:
谁能帮我解决这个问题。我用两个模型创建了一个 django-app。 一种模型是钱包模型,另一种是交易模型。每笔交易都通过models.ForeignKey连接到一个钱包。我还创建了两个信号,一个用于在进行交易时更新钱包中的加密货币余额(例如 BTC、ETH),另一个用于更新 Total_Balance(将所有其他余额转换为美元)。在这里我遇到了一个问题,因为我的信号是 POST_SAVE 并且在其中我有一个导致无限循环的 save() 方法。我想如果我在我的第一个信号中做一整件事,它会起作用,但将来我想添加新模型,它也将连接到钱包,它会弹出我的 total_balance,因此我需要在第三个信号中使用相同的逻辑我最终会在两个信号中得到相同的代码。
我知道我的描述有点混乱。这里有一些代码可以帮助理解它。
我的模特:
class Wallet(models.Model):
name = models.CharField(max_length=50)
total_balance = models.IntegerField(blank=True)
btc_balance = models.DecimalField(max_digits=15, decimal_places=8)
xrp_balance = models.DecimalField(max_digits=15, decimal_places=8)
eth_balance = models.DecimalField(max_digits=15, decimal_places=8)
class Transaction(models.Model):
wallet = models.ForeignKey(Wallet, on_delete=models.CASCADE)
currency_paid = models.CharField(choices=CURRENCY, max_length=3)
amount_paid = models.DecimalField(max_digits=15, decimal_places=8)
currency_recived = models.CharField(choices=CURRENCY, max_length=3)
amount_recived = models.DecimalField(max_digits=15, decimal_places=8)
我的信号:
@receiver(post_save, sender=Transaction)
def create_transaction(sender, instance, created, **kwargs):
if created:
wallet = Wallet.objects.get(name = instance.wallet)
currency_paid = instance.currency_paid
currency_recived = instance.currency_recived
amount_paid = instance.amount_paid
amount_recived = instance.amount_recived
# SUBSTRACK BALANCE
if(currency_paid == 'BTC'):
wallet.btc_balance -= amount_paid
...
# ADDS BALANCE
if(currency_recived == 'BTC'):
wallet.btc_balance += amount_recived
...
wallet.save()
@receiver(post_save, sender=Wallet)
def total_balance_update(sender, instance, created, **kwargs):
if created == False:
btc_price = cryptocompare.get_price('BTC',curr='USD')['BTC']['USD']
xrp_price = cryptocompare.get_price('XRP',curr='USD')['XRP']['USD']
...
btc_balance = float(instance.btc_balance)
xrp_balance = float(instance.xrp_balance)
...
total_balance = instance.total_balance
total_balance = round(btc_balance * btc_price) + round(xrp_balance * xrp_balance) + round(eth_balance * eth_balance)
instance.save()
【问题讨论】:
-
Wallet的post_save包含一个instance.save()。所以这意味着如果你.save()一个钱包,信号将再次运行保存钱包(因此再次等) -
是的,我知道,这就是我寻求帮助的原因,我能做些什么不同
标签: python django django-models django-signals