我想知道如何在我的代码中将数据添加到 ins.save
之后的 Django 整数字段。例如,如果捐赠字段等于 3,在 ins.save
之后,我想给它加 1,因此它等于 4。我的代码在下面。
捐赠 View :
def donate(request):
if request.method == "POST":
title = request.POST['donationtitle']
phonenumber = request.POST['phonenumber']
category = request.POST['category']
quantity = request.POST['quantity']
location = request.POST['location']
description = request.POST['description']
ins = Donation(title = title, phonenumber = phonenumber, category = category, quantity = quantity, location = location, description = description, user=request.user, )
ins.save()
return render(request,'donate.html')
最佳答案
你可以试试这个。
from django.db.models import F
......
ins.save()
UserDetail.objects.filter(user=request.user).update(donations=F('donations') + 1)
这将使 request.user
的捐款在 ins.save()
之后增加 1
此外,不要为 UserDetail 模型中的 IntegerField 将可为空的捐赠字段设置默认值为零
class UserDetail(models.Model):
donations = models.IntegerField(default=0)
关于python - 如何更新 Django 模型数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68152173/