Refs -- Cleaned up try/except blocks in loaddata command.
This moves code unable to trigger relevant exceptions outside of
try/except blocks, and changes 'objects' to 'objects_in_fixture'
which is equal to the length of 'objects'.
@@ -117,8 +117,8 @@ class Command(BaseCommand):
else:
return
- with connection.constraint_checks_disabled():
self.objs_with_deferred_fields = []
+ with connection.constraint_checks_disabled():
for fixture_label in fixture_labels:
self.load_label(fixture_label)
for obj in self.objs_with_deferred_fields:
@@ -163,7 +163,6 @@ class Command(BaseCommand):
_, ser_fmt, cmp_fmt = self.parse_name(os.path.basename(fixture_file))
open_method, mode = self.compression_formats[cmp_fmt]
fixture = open_method(fixture_file, mode)
- try:
self.fixture_count += 1
objects_in_fixture = 0
loaded_objects_in_fixture = 0
@@ -172,7 +171,7 @@ class Command(BaseCommand):
"Installing %s fixture '%s' from %s."
% (ser_fmt, fixture_name, humanize(fixture_dir))
)
-
+ try:
objects = serializers.deserialize(
ser_fmt, fixture, using=self.using, ignorenonexistent=self.ignore,
handle_forward_references=True,
@@ -188,11 +187,6 @@ class Command(BaseCommand):
self.models.add(obj.object.__class__)
try:
obj.save(using=self.using)
- if show_progress:
- self.stdout.write(
- '\rProcessed %i object(s).' % loaded_objects_in_fixture,
- ending=''
- )
# psycopg2 raises ValueError if data contains NUL chars.
except (DatabaseError, IntegrityError, ValueError) as e:
e.args = ("Could not load %(object_label)s(pk=%(pk)s): %(error_msg)s" % {
@@ -201,12 +195,13 @@ class Command(BaseCommand):
'error_msg': e,
},)
raise
+ if show_progress:
+ self.stdout.write(
+ '\rProcessed %i object(s).' % loaded_objects_in_fixture,
+ ending=''
+ )
if obj.deferred_fields:
self.objs_with_deferred_fields.append(obj)
- if objects and show_progress:
- self.stdout.write() # Add a newline after progress indicator.
- self.loaded_object_count += loaded_objects_in_fixture
- self.fixture_object_count += objects_in_fixture
except Exception as e:
if not isinstance(e, CommandError):
e.args = ("Problem installing fixture '%s': %s" % (fixture_file, e),)
@@ -214,6 +209,10 @@ class Command(BaseCommand):
finally:
fixture.close()
+ if objects_in_fixture and show_progress:
+ self.stdout.write() # Add a newline after progress indicator.
+ self.loaded_object_count += loaded_objects_in_fixture
+ self.fixture_object_count += objects_in_fixture
# Warn if the fixture we loaded contains 0 objects.
if objects_in_fixture == 0:
warnings.warn(
