bulk_demo.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # Copyright © 2023 Ingram Micro Inc. All rights reserved.
  2. import random
  3. from django.core.management.base import BaseCommand
  4. from django.db import transaction
  5. from tests.dj_master.models import Author, Book, Publisher
  6. class Command(BaseCommand):
  7. help = 'Simulate N signals.'
  8. def add_arguments(self, parser):
  9. parser.add_argument(
  10. '--count',
  11. '-c',
  12. help='Simulation of N signals.',
  13. type=int,
  14. default=3000,
  15. )
  16. @staticmethod
  17. def _get_max_id(model):
  18. try:
  19. return model.objects.all().order_by('-id')[0].id
  20. except IndexError:
  21. return 0
  22. def handle(self, *args, **options):
  23. max_author_id = self._get_max_id(Author)
  24. max_book_id = self._get_max_id(Book)
  25. max_publisher_id = self._get_max_id(Publisher)
  26. with transaction.atomic():
  27. for _ in range(options['count']):
  28. publisher = None
  29. if bool(random.getrandbits(1)):
  30. max_publisher_id += 1
  31. publisher = Publisher.objects.create(id=max_publisher_id, name='p')
  32. max_author_id += 1
  33. author = Author.objects.create(id=max_author_id, name='a', publisher=publisher)
  34. for _ in range(random.randint(0, 2)):
  35. max_book_id += 1
  36. Book.objects.create(id=max_book_id, title='t', author=author)