Django嵌套事务和异常

2024-05-18 14:30:17 发布

您现在位置:Python中文网/ 问答频道 /正文

为了简单起见,我的代码中有一个嵌套的原子事务,基本上如果向电影中添加人失败(请参见第一个循环),我希望显示一个异常,特别说明此操作失败,并且回滚movie.save(),对于电影公司也是如此(请参见第二个循环)。但是由于某种原因,当其中任何一个失败时movie.save()不会回滚,我会在数据库中保存一部电影,而没有任何人或工作室连接到它

people = ['Mark', 'John', 'Mark']
studios = ['Universal Studios', 'Longcross Studios']

try:
    with transaction.atomic():
        movie = Movie(title=title, description=summary, pub_date=pub_date)
        movie.save()

        # iterate through people list, get the pk from database and add it to the movie
        try:
            with transaction.atomic():
                for p in people:
                    person = Person.objects.get(name=p)
                    movie.people.add(person)

        except Person.DoesNotExist:
            self.stdout.write(self.style.ERROR('One or more performers from %s does not '
                                               'exist in database, please add them and '
                                               'rerun the command.' % str(people)))
            continue

        # iterate through studio list, get the pk from database and add it to the movie
        try:
            with transaction.atomic():
                for s in studios:
                    studio = Studio.objects.get(name=s)
                    movie.studios.add(studio)
        except Studio.DoesNotExist:
            self.stdout.write(self.style.ERROR('One or more studios from %s does not '
                                               'exist in database, please add them and '
                                               'rerun the command.' % str(studios)))
            continue

        movie.save()
        self.stdout.write(self.style.NOTICE('Successfully added movie %s' % title))

except Exception as e:
    self.stdout.write(self.style.ERROR('Failed to add movie to the database.'))

Tags: andthetoinfromselfaddget
1条回答
网友
1楼 · 发布于 2024-05-18 14:30:17

当异常退出atomic块时发生回滚。但是您正在捕获异常并抑制它们,因此不会发生回滚。要让异常在记录消息后传播,需要使用raise,而不是continue

相关问题 更多 >

    热门问题