make_bulk_events.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from django.core.management.base import BaseCommand
  2. from model_bakery import baker
  3. from model_bakery.random_gen import gen_json, gen_slug
  4. from events.models import Event
  5. from events.test_data import event_generator
  6. from issues.models import Issue
  7. from issues.tasks import update_search_index_issue
  8. from organizations_ext.models import Organization
  9. from projects.models import Project
  10. from projects.tasks import update_event_project_hourly_statistic
  11. from events.test_data import bulk_event_data
  12. baker.generators.add("organizations.fields.SlugField", gen_slug)
  13. baker.generators.add("django.db.models.JSONField", gen_json)
  14. class Command(BaseCommand):
  15. help = "Create an issue with a large number of events for dev and demonstration purposes"
  16. def add_arguments(self, parser):
  17. parser.add_argument("quantity", nargs="?", type=int, default=10000)
  18. parser.add_argument("batch_size", nargs="?", type=int, default=10000)
  19. def handle(self, *args, **options):
  20. organization = Organization.objects.first()
  21. if not organization:
  22. organization = baker.make("organizations_ext.Organization")
  23. project = Project.objects.filter(organization=organization).first()
  24. if not project:
  25. project = baker.make("projects.Project", organization=organization)
  26. issue_data = bulk_event_data.large_event
  27. title = issue_data.get("title")
  28. culprit = issue_data.get("culprit")
  29. metadata = issue_data.get("metadata")
  30. issue, _ = Issue.objects.get_or_create(
  31. title=title,
  32. culprit=culprit,
  33. metadata=metadata,
  34. project=project,
  35. )
  36. quantity = options["quantity"]
  37. batch_size = options["batch_size"]
  38. if quantity < batch_size:
  39. batches = 1
  40. else:
  41. batches = quantity // batch_size
  42. for _ in range(batches):
  43. if quantity < batch_size:
  44. batch_size = quantity
  45. event_list = []
  46. for _ in range(batch_size):
  47. event = Event(
  48. data=event_generator.make_event_unique(bulk_event_data.large_event),
  49. issue=issue,
  50. )
  51. event_list.append(event)
  52. Event.objects.bulk_create(event_list)
  53. quantity -= batch_size
  54. update_search_index_issue(args=[issue.pk])
  55. update_event_project_hourly_statistic(args=[project.pk, event.created])
  56. self.stdout.write(
  57. self.style.SUCCESS('Successfully created "%s" events' % options["quantity"])
  58. )