Closed as duplicate of#7
Description
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
Labels
No labels