Skip to content

transaction.atomic() does not work #268

Closed as duplicate of#7
Closed as duplicate of#7
@hancens1024

Description

@hancens1024

test raise an exception. the first book "Harry Potter and the Philosopher's Stone" still saved to db

from django.test import TestCase

from django.db import models, transaction


class Author(models.Model):
    name = models.CharField(max_length=100)


class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)


# Create your tests here.
class TestTransaction(TestCase):

    def test_transaction(self):
        try:
            with transaction.atomic():
                author = Author.objects.create(name="J.K. Rowling")

                Book.objects.create(title="Harry Potter and the Philosopher's Stone", author=author)

                raise Exception("Simulating an error to test transaction rollback.")

                Book.objects.create(title="Harry Potter and the Chamber of Secrets", author=author)

            print("Transaction test completed successfully.")

        except Exception as e:
            print(f"Transaction failed. Error: {str(e)}")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions