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 supplying _quantity parameter to baker.make #65

Closed
abbottc opened this issue Feb 12, 2020 · 3 comments · Fixed by #134
Closed

Use bulk_create when supplying _quantity parameter to baker.make #65

abbottc opened this issue Feb 12, 2020 · 3 comments · Fixed by #134

Comments

@abbottc
Copy link
Contributor

abbottc commented Feb 12, 2020

I noticed that when using the _quantity parameter with baker.make, each model instance is added to the database individually (see this line: https://github.com/model-bakers/model_bakery/blob/master/model_bakery/baker.py#L356).

Would it be reasonable to use django's bulk_create manager method to create them all in one database query in that situation? The difference in efficiency could be significant when running test suites which use that parameter often enough.

@timjklein36
Copy link
Collaborator

It may not make sense to use bulk_create for all use cases. Consider the caveats listed in the Django docs. Mainly:

  • The model’s save() method will not be called, and the pre_save and post_save signals will not be sent.
  • It does not work with many-to-many relationships.

With that in mind, we could expose a second attribute related to _quantity called _bulk or _bulk_create which enables the suggested behavior.

@berinhard
Copy link
Member

Totally agree with you @timjklein36!

This fix shouldn't change bakery's default behavior of calling save, but enables it to use bulk create if the caller wants too. I'm a +1 from having a _bulk_create flag which defaults to False and, if flagged as True it would change bakery's internals to use bulk_create instead of calling save method. And, yep, this won't work with M2M relationships.

@timjklein36
Copy link
Collaborator

Working on a PR now that adds _bulk_create parameter to use make -> prepare many + bulk_create (instead of make -> save many) when supplied with _quantity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants