truncate.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from django.core.management.base import BaseCommand, CommandError
  2. from django.apps import apps
  3. class Command(BaseCommand):
  4. appsList = [] # this list will have all wanted apps
  5. modelsList = [] # this list will have all wanted models
  6. def add_arguments(self, parser):
  7. parser.add_argument('--models',
  8. nargs='*',
  9. type=str,
  10. dest='models',
  11. default=None,
  12. help="This will take the names of the wanted models")
  13. parser.add_argument('--apps',
  14. nargs='*',
  15. type=str,
  16. dest='apps',
  17. default=None,
  18. help='Collect wanted apps to get there models, default will be getting all models of the project')
  19. def handle(self, *args, **options):
  20. if options['apps'] == None or options['apps'] == [] or options['apps'] == ['']:
  21. print('No apps was entered')
  22. else:
  23. print('Fetching apps...')
  24. for someApp in options['apps']:
  25. try:
  26. self.appsList.append(apps.get_app_config(someApp))
  27. except LookupError:
  28. print("The app " + someApp + " does not exist")
  29. print('Finished apps fetching')
  30. if options['models'] == None or options['models'] == [] or options['models'] == ['']:
  31. print("No models were called")
  32. elif self.appsList:
  33. print("Fetching models...")
  34. for appConf in self.appsList:
  35. for someModel in options['models']:
  36. try:
  37. self.modelsList.append(appConf.get_model(someModel))
  38. except LookupError:
  39. print("The model " + someModel + " does not exist in this app")
  40. if not self.modelsList:
  41. self.appsList = []
  42. print('Finished models fetching')
  43. if not self.modelsList and not self.appsList:
  44. print('Nothing was called')
  45. elif self.appsList and not self.modelsList:
  46. print('Starting apps truncate..')
  47. for _app in self.appsList:
  48. app_models = _app.get_models()
  49. for _model in app_models:
  50. _model.objects.all().delete()
  51. print("The " + _app.name + " app is now empty")
  52. print('Finished apps truncate!')
  53. else:
  54. for _model in self.modelsList:
  55. _model.objects.all().delete()
  56. print('Finished models truncate!')