python - 如何更新 Django 模型数据

标签 python html css django django-models

我想知道如何在我的代码中将数据添加到 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/

相关文章:

python - 语法错误 : unexpected EOF while parsing (using . 格式())

python - 'utf- 8' codec can' t 解码字节读取 Python3.4 中的文件,但不是 Python2.7

html - 如何在 CSS 边框的直线部分留下间隙

html - 漂浮在容器 Div 之外的 block

html - CSS - 绝对定位的移动响应问题

CSS混合相对和绝对高度

python - 导入pylab时matplotlib "DLL load failed"

python - 使用 PySpark 将日期和时间字符串转换为时间戳时如何保留毫秒?

c# - 如何将asp-append-version ="true"实现到background-image属性?

javascript - 网页不呈现使用 Javascript 添加的图片