Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature enhancement: option to truncate model tables before seeding #108

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions django_seed/management/commands/seed.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ def add_arguments(self, parser: argparse.ArgumentParser):
required=False, type=str, help=help_text,
metavar=('model.field', 'value'), dest='seeder')

help_text = 'Truncate app tables before seeding.'
parser.add_argument('--truncate', action='store_true',
default=False, required=False,
help=help_text, dest='truncate')

def handle_app_config(self, app_config, **options):
if app_config.models_module is None:
raise SeederCommandError('You must provide an app to seed')
Expand Down Expand Up @@ -50,6 +55,15 @@ def handle_app_config(self, app_config, **options):
seeder.add_entity(model, number, seeders[model.__name__])
else:
seeder.add_entity(model, number)

if options['truncate']:
self.stdout.write(f"Truncating {model.__name__} before seeding...",
style_func=self.style.WARNING)
manager = model.objects.db_manager()
total, _ = manager.all().delete()
self.stdout.write(f"Removed {total} {model.__name__} objects.",
style_func=self.style.WARNING)

self.stdout.write('Seeding %i %ss' % (number, model.__name__))

generated = seeder.execute()
Expand Down
6 changes: 4 additions & 2 deletions django_seed/seeder.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,16 +213,18 @@ def add_entity(self, model, number, customFieldFormatters=None):
}
self.orders.append(order)

def execute(self, using=None, inserted_entities={}):
def execute(self, using=None, inserted_entities=None):
"""
Populate the database using all the Entity classes previously added.
:param using A Django database connection name
:rtype: A list of the inserted PKs
"""
if inserted_entities is None:
inserted_entities = {}

if not using:
using = self.get_connection()

inserted_entities = {}
while len(self.orders):
order = self.orders.pop(0)
number = order["quantity"]
Expand Down