From 1d96d886e7f36fcee918b7fa5c32b677bed83b0d Mon Sep 17 00:00:00 2001 From: Paul McMillan Date: Thu, 22 Sep 2011 04:30:20 +0000 Subject: [PATCH] Fixed #16026 -- loaddata now identifies which object triggered an error. git-svn-id: http://code.djangoproject.com/svn/django/trunk@16873 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/core/management/commands/loaddata.py | 14 ++++++++++++-- tests/modeltests/fixtures/tests.py | 11 +++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py index 6b2b9e9b2e3..7b0e30fbb47 100644 --- a/django/core/management/commands/loaddata.py +++ b/django/core/management/commands/loaddata.py @@ -12,7 +12,8 @@ from django.conf import settings from django.core import serializers from django.core.management.base import BaseCommand from django.core.management.color import no_style -from django.db import connections, router, transaction, DEFAULT_DB_ALIAS +from django.db import (connections, router, transaction, DEFAULT_DB_ALIAS, + IntegrityError, DatabaseError) from django.db.models import get_apps from django.utils.itercompat import product @@ -177,7 +178,16 @@ class Command(BaseCommand): if router.allow_syncdb(using, obj.object.__class__): loaded_objects_in_fixture += 1 models.add(obj.object.__class__) - obj.save(using=using) + try: + obj.save(using=using) + except (DatabaseError, IntegrityError), e: + msg = "Could not load %(app_label)s.%(object_name)s(pk=%(pk)s): %(error_msg)s" % { + 'app_label': obj.object._meta.app_label, + 'object_name': obj.object._meta.object_name, + 'pk': obj.object.pk, + 'error_msg': e + } + raise e.__class__, e.__class__(msg), sys.exc_info()[2] # Since we disabled constraint checks, we must manually check for # any invalid keys that might have been added diff --git a/tests/modeltests/fixtures/tests.py b/tests/modeltests/fixtures/tests.py index c335ffbc272..de78d0b4fdf 100644 --- a/tests/modeltests/fixtures/tests.py +++ b/tests/modeltests/fixtures/tests.py @@ -252,6 +252,17 @@ class FixtureLoadingTests(TestCase): '' ]) + def test_loaddata_error_message(self): + """ + Verifies that loading a fixture which contains an invalid object + outputs an error message which contains the pk of the object + that triggered the error. + """ + new_io = StringIO.StringIO() + management.call_command('loaddata', 'invalid.json', verbosity=0, stderr=new_io, commit=False) + output = new_io.getvalue().strip().split('\n') + self.assertRegexpMatches(output[-1], "IntegrityError: Could not load fixtures.Article\(pk=1\): .*$") + def test_loading_using(self): # Load db fixtures 1 and 2. These will load using the 'default' database identifier explicitly management.call_command('loaddata', 'db_fixture_1', verbosity=0, using='default', commit=False)