为什么我的保存方法不返回任何值



当我这样做的时候:

investment.basic_interest

得到0。为什么它返回0?我觉得我的保存方法写得不对。知道问题是怎么来的吗?

Models.py:

class Investment(models.Model):
basic_deposit_amount = models.IntegerField(null=True)
basic_interest = models.IntegerField(null=True)
def save(self, *args, **kwargs):
self.basic_interest =  self.basic_deposit_amount * 365 * 0.02/2  #calculated field. 
super(Investment, self).save(*args, **kwargs)

views.py:

def create_investment_view(request):
if request.method == 'POST':
basic_investment_form = BasicInvestmentForm(request.POST)

if basic_investment_form.is_valid():
investment = basic_investment_form.save(commit=False)
investment.basic_investment_return += investment.basic_deposit_amount
print(investment.basic_interest)
print(investment.basic_investment_return)
print(investment.basic_deposit_amount)
investment.is_active = True
investment.save()
messages.success(request, 'your basic investment of {} is successfull '.format(investment.basic_deposit_amount))
else:
messages.success(request, 'your investment is not successfull! Try again.')
else:
basic_investment_form = BasicInvestmentForm()

context = {'basic_investment_form': basic_investment_form}
return render(request, 'create-basic-investment.html', context)

这取决于您在代码中检查investment.basic_interest值的位置。只有当实例被保存时(在调用save()方法之后),才会执行这段代码。

def test_view(request):
investment = Investment()
investment.basic_deposit_amount = 100
print(investment.basic_interest) # Prints 0
investment.save()
print(investment.basic_interest) # Prints 365.0

您需要返回super()方法所做的。添加return到最后一行:

def save(self, *args, **kwargs):
self.basic_interest =  self.basic_deposit_amount * 365 * 0.02/2  #calculated field. 
return super(Investment, self).save(*args, **kwargs)

相关内容

  • 没有找到相关文章

最新更新