我是Django的新手,并且有一些模型定义如下:
class ProjectModel(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
class Meta:
db_table = "projects"
class StudyModel(models.Model):
project = models.ForeignKey(ProjectModel)
name = models.CharField(max_length=100)
description = models.TextField()
class Meta:
db_table = "studies"
我有一个关联视图,允许用户同时创建项目和研究。我这样做:
pid = ProjectModel.objects.filter(name__iexact=project_name).first()
if pid is None:
try:
#with transaction.atomic():
pobj = ProjectModel.objects.create(name="A", description="")
sobj = StudyModel.objects.create(name="B", description="", project_id=pobj.pk)
except:
#pobj.delete()
#sobj.delete()
return Response(status=status.HTTP_417_EXPECTATION_FAILED)
我一直在考虑如何执行此操作,以便在任何操作失败时,数据库保持不变,即如果由于某种原因未创建study
,则不会创建project
我认为可行的一种方法是在调用savepoints
之前标记方法objects.create
,然后在异常处理程序中回滚。但是,我不确定这是否是正确的方法。
答案 0 :(得分:1)
使用transaction.atomic
(就像您已注释掉的那样)将操作包装到单个数据库事务中。
from django.db import DatabaseError, transaction
if pid is None:
try:
with transaction.atomic():
pobj = ProjectModel.objects.create(name="A", description="")
sobj = StudyModel.objects.create(name="B", description="", project_id=pobj.pk)
except DatabaseError:
return Response(status=status.HTTP_417_EXPECTATION_FAILED)