简体   繁体   English

Django中用于相关操作的数据库事务

[英]database tranactions in django for dependent operations

I am new to Django and have some model definitions as follows: 我是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"

I have an associated view which allows the user to create a project and a study at the same time. 我有一个关联的视图,该视图允许用户同时创建项目和研究。 I do it as follows: 我这样做如下:

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)

I have been thinking about how to do this so that if any of the operations fail, the database stays untouched ie if the study is not created for some reason, the project is not created either. 我一直在考虑如何执行此操作,以便如果任何操作失败,数据库将保持不变,即,如果由于某种原因未创建study则也不会创建project

One way i thought it is doable is to mark the method savepoints before calling the objects.create and then rolling back in the exception handler. 我认为可行的一种方法是在调用objects.create之前标记方法savepoints ,然后在异常处理程序中回滚。 However, I am not sure if that is the right way to do this. 但是,我不确定这是否是正确的方法。

Use transaction.atomic (like you have commented out) to wrap operations into single, database transaction. 使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM