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

Use bulk_create when creating batches in Django #764

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions examples/flask_alchemy/demoapp_factories.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import demoapp

import factory.alchemy
import factory.fuzzy

Expand Down
15 changes: 15 additions & 0 deletions factory/django.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,21 @@ def _create(cls, model_class, *args, **kwargs):
manager = cls._get_manager(model_class)
return manager.create(*args, **kwargs)

@classmethod
def create_batch(cls, size, **kwargs):
"""Create a batch of instances of the given class, with overriden attrs.

Args:
size (int): the number of instances to create

Returns:
object list: the created instances
"""

model_class = cls._meta.get_model_class()
manager = cls._get_manager(model_class)
return manager.bulk_create(cls.build_batch(size, **kwargs))

@classmethod
def _after_postgeneration(cls, instance, create, results=None):
"""Save again the instance if creating and at least one hook ran."""
Expand Down
5 changes: 2 additions & 3 deletions tests/test_django.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,11 +218,10 @@ def test_missing_arg(self):

def test_multicall(self):
objs = MultifieldModelFactory.create_batch(
6,
2,
slug=factory.Iterator(['main', 'alt']),
)
self.assertEqual(6, len(objs))
self.assertEqual(2, len(set(objs)))
self.assertEqual(2, len(objs))
self.assertEqual(
list(
models.MultifieldModel.objects.order_by("slug").values_list(
Expand Down
7 changes: 7 additions & 0 deletions tests/test_using.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,13 @@ def create(self, **kwargs):
instance._defaults = None
return instance

def bulk_create(self, instances):
for instance in instances:
instance.id = 2
instance._defaults = None

return instances

def values_list(self, *args, **kwargs):
return self

Expand Down