【发布时间】:2018-11-19 19:19:28
【问题描述】:
进行新投资时,我正在使用信号更新配置文件表中的字段。
在 update_users_investments 函数中使用了许多打印语句,我可以看到该函数正在被调用并且它正在执行正确的计算。
但是,它没有保存到数据库中,也没有错误。
你能明白为什么它没有保存吗?有没有更好的方法来调试保存方法?我环顾四周,看不到任何东西,不知道为什么没有保存非常令人沮丧。
在我的代码的其他地方,我使用类似的信号保存到其他看起来工作正常的表中。
信号
@receiver(post_save, sender=Investment)
def update_users_investments(sender, instance, created, **kwargs):
user = Profile.objects.get(user=instance.user.user)
total_investments = user.total_invested
investment = instance.transaction_type * instance.price * instance.number_shares
user.total_invested = total_investments + investment
user.save()
要保存到的模型:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
total_invested = models.DecimalField(max_digits=5, decimal_places=2)
cash_avaliable = models.DecimalField(max_digits=5, decimal_places=2,
null=True)
投资模型(信号的来源):
class Investment(models.Model):
"""Model representing each investment made by users"""
user = models.ForeignKey(Profile, on_delete=models.DO_NOTHING)
team_code = models.ForeignKey(Team,
on_delete=models.DO_NOTHING)
transaction_type = models.IntegerField(choices=((-1, "Sell"), (1, "Buy")),
help_text="Show whether transaction\
was a buy or sell",
verbose_name="Transaction Type")
number_shares = models.IntegerField(help_text="Number of shares bought or \
sold in this transaction",
verbose_name="Number of Shares")
price = models.DecimalField(help_text = "Current Price of the team",
verbose_name = "Current Price", decimal_places=2, max_digits=5)
transaction_date = models.DateTimeField(auto_now=True, help_text="Date and \
Time of transaction",
verbose_name="Transaction Date")
transaction_mode = models.IntegerField(choices=((-1, "User Generated"),
(1,
"Automatically Generated")))
编辑
已经解决了这个问题 - 正如所指出的, user = Profile.objects.get(user=instance.user.user) 不是必需的。
@receiver(post_save, sender=Investment)
def update_users_investments(sender, instance, created, **kwargs):
total_investments = instance.user.total_invested
investment = instance.transaction_type * instance.price * instance.number_shares
instance.user.total_invested = total_investments + investment
instance.user.save()
现在看来让它工作了:-)
【问题讨论】:
-
请更正代码中的缩进。
-
你为什么打电话给
user = Profile.objects.get(user=instance.user.user)?user = instance.user不会做同样的事情吗?你怎么知道Profile没有保存?investment是否可能为零?那么就没有变化了。 -
感谢@HåkenLid - 也对标识进行了排序并添加了编辑。投资不能为零,但要重新编写信号中的代码以使其工作。谢谢!
标签: django django-models django-signals