gpt4 book ai didi

python - 在基于类的 View 中使用@transaction.atomic 保存模型

转载 作者:行者123 更新时间:2023-11-28 18:23:15 24 4
gpt4 key购买 nike

我正在尝试同时处理添加新对象和编辑对象。我的 views.py 文件就像-

personal_data=Personal.objects.create(emp_fname=first_name, emp_mname=middle_name, emp_lname=last_name)
# rest of object is created here
try:
print "pk", pk
with transaction.atomic():
if pk != None:
print "hey"
#save model goes here
messages.add_message(request, messages.INFO, 'Data updated successfully')
else:
print "hello"
personal_data.save()
family_data.save()
address_data.save()
education_data.save()
pre_company_data.save()
messages.add_message(request, messages.INFO, 'Data saved successfully')
except IntegrityError:
handle_exception()

if-else 条件正常工作,但在这两种情况下都保存了数据。即使我评论了上面显示的代码,数据仍然会进入数据库。

最佳答案

如果你的意思是在两种情况下都保存了 personal_data,那是因为你正在调用 Personal.objects.create,它一步创建模型并将其保存在数据库中(引用:https://docs.djangoproject.com/en/dev/topics/db/queries/#creating-objects ).如果您想将创建与保存分开,请使用通常的构造函数创建模型:

personal_data = Personal(emp_fname=first_name, emp_mname=middle_name, emp_lname=last_name)

try:
with transaction.atomic():
if pk != None:
# do stuff
else:
personal_data.save()
# do some other stuff
except IntegrityError:
handle_exception()

在这种情况下,personal_data 模型将保存在else 分支中。

关于python - 在基于类的 View 中使用@transaction.atomic 保存模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43422987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com