我的模特
class Credits(models.Model):
creds = models.IntegerField(default=0)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
我的观点
def addjobdata(request):
n = JobInfo.objects.create(title=request.POST['title'], start_date=timezone.now(), end_date=timezone.now() + datetime.timedelta(days=int(request.POST['days'])), rate=request.POST['rate'] )
if int(Credits.objects.get(user_id=request.user).creds) > int(request.POST['days']):
Credits.objects.get(user_id=request.user).creds -= int(request.POST['days'])
Credits.objects.get(user_id=request.user).creds.save()
return HttpResponseRedirect(reverse('datedisplay:infos', args=(n.id,)))
else:
return render(request, 'datedisplay/menu.html')
在if循环中,我试图从整数字段中取一个数字并保存结果,但我没有这样做。我搞砸了哪些想法?
答案 0 :(得分:1)
您反复查询同一个对象。除了数据库上不必要的负载之外,每次查询时都会得到一个新对象,该对象不包含您所做的更改。
而是查询一次并保存到变量:
cred = Credits.objects.get(user=request.user)
days = int(request.POST['days'])
if cred.creds > days:
cred.creds -= days
cred.save()
return HttpResponseRedirect(reverse('datedisplay:infos', args=(n.id,)))
另请注意,您需要保存Credits实例本身,而不是creds
属性。