Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #16340 -- Made `get_or_create()` re-raise any `IntegrityError` …

…with its original traceback. Thanks to d0ugal and Jonas Obrist.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@17333 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 31b1cbc623c246570e7301c0334df938d840638f 1 parent fc9e060
Julien Phalip authored January 02, 2012
5  django/db/models/query.py
@@ -4,6 +4,7 @@
4 4
 
5 5
 import copy
6 6
 import itertools
  7
+import sys
7 8
 
8 9
 from django.db import connections, router, transaction, IntegrityError
9 10
 from django.db.models.fields import AutoField
@@ -450,10 +451,12 @@ def get_or_create(self, **kwargs):
450 451
                 return obj, True
451 452
             except IntegrityError, e:
452 453
                 transaction.savepoint_rollback(sid, using=self.db)
  454
+                exc_info = sys.exc_info()
453 455
                 try:
454 456
                     return self.get(**lookup), False
455 457
                 except self.model.DoesNotExist:
456  
-                    raise e
  458
+                    # Re-raise the IntegrityError with its original traceback.
  459
+                    raise exc_info[1], None, exc_info[2]
457 460
 
458 461
     def latest(self, field_name=None):
459 462
         """
12  tests/modeltests/get_or_create/tests.py
... ...
@@ -1,6 +1,7 @@
1 1
 from __future__ import absolute_import
2 2
 
3 3
 from datetime import date
  4
+import traceback
4 5
 
5 6
 from django.db import IntegrityError
6 7
 from django.test import TestCase
@@ -52,3 +53,14 @@ def test_get_or_create(self):
52 53
             ManualPrimaryKeyTest.objects.get_or_create, id=1, data="Different"
53 54
         )
54 55
         self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, "Original")
  56
+
  57
+        # get_or_create should raise IntegrityErrors with the full traceback.
  58
+        # This is tested by checking that a known method call is in the traceback.
  59
+        # We cannot use assertRaises/assertRaises here because we need to inspect
  60
+        # the actual traceback. Refs #16340.
  61
+        try:
  62
+            ManualPrimaryKeyTest.objects.get_or_create(id=1, data="Different")
  63
+        except IntegrityError, e:
  64
+            formatted_traceback = traceback.format_exc()
  65
+            self.assertIn('obj.save', formatted_traceback)
  66
+

0 notes on commit 31b1cbc

Please sign in to comment.
Something went wrong with that request. Please try again.