createfakecategories.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import random
  2. import time
  3. from django.core.management.base import BaseCommand
  4. from faker import Factory
  5. from ....acl.cache import clear_acl_cache
  6. from ....categories.models import Category, RoleCategoryACL
  7. from ....core.management.progressbar import show_progress
  8. class Command(BaseCommand):
  9. help = "Creates fake categories for dev and testing purposes."
  10. def add_arguments(self, parser):
  11. parser.add_argument(
  12. "categories",
  13. help="number of categories to create",
  14. nargs="?",
  15. type=int,
  16. default=5,
  17. )
  18. parser.add_argument(
  19. "minlevel",
  20. help="min. level of created categories",
  21. nargs="?",
  22. type=int,
  23. default=0,
  24. )
  25. def handle(self, *args, **options):
  26. items_to_create = options["categories"]
  27. min_level = options["minlevel"]
  28. categories = Category.objects.all_categories(True)
  29. copy_acl_from = list(Category.objects.all_categories())[0]
  30. categories = categories.filter(level__gte=min_level)
  31. fake = Factory.create()
  32. message = "Creating %s fake categories...\n"
  33. self.stdout.write(message % items_to_create)
  34. created_count = 0
  35. start_time = time.time()
  36. show_progress(self, created_count, items_to_create)
  37. while created_count < items_to_create:
  38. parent = random.choice(categories)
  39. new_category = Category()
  40. if random.randint(1, 100) > 75:
  41. new_category.set_name(fake.catch_phrase().title())
  42. else:
  43. new_category.set_name(fake.street_name())
  44. if random.randint(1, 100) > 50:
  45. if random.randint(1, 100) > 80:
  46. new_category.description = "\r\n".join(fake.paragraphs())
  47. else:
  48. new_category.description = fake.paragraph()
  49. new_category.insert_at(parent, position="last-child", save=True)
  50. copied_acls = []
  51. for acl in copy_acl_from.category_role_set.all():
  52. copied_acls.append(
  53. RoleCategoryACL(
  54. role_id=acl.role_id,
  55. category=new_category,
  56. category_role_id=acl.category_role_id,
  57. )
  58. )
  59. if copied_acls:
  60. RoleCategoryACL.objects.bulk_create(copied_acls)
  61. created_count += 1
  62. show_progress(self, created_count, items_to_create, start_time)
  63. clear_acl_cache()
  64. total_time = time.time() - start_time
  65. total_humanized = time.strftime("%H:%M:%S", time.gmtime(total_time))
  66. message = "\n\nSuccessfully created %s fake categories in %s"
  67. self.stdout.write(message % (created_count, total_humanized))