Skip to content

Commit

Permalink
Fix #385 -- Handle bulk creation when using reverse related name (#486)
Browse files Browse the repository at this point in the history
* Fix issue and add test coverage (#385)

* Reuse existing test models, check the query count

---------

Co-authored-by: Suraj Magdum <[email protected]>
  • Loading branch information
amureki and magdumsuraj07 authored Aug 9, 2024
1 parent 5aa3070 commit 6784e68
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
### Added

### Changed
- Handle bulk creation when using reverse related name

### Removed

Expand Down
14 changes: 14 additions & 0 deletions model_bakery/baker.py
Original file line number Diff line number Diff line change
Expand Up @@ -864,4 +864,18 @@ def bulk_create(baker: Baker[M], quantity: int, **kwargs) -> List[M]:
for obj in kwargs[field.name]
]
)

# set many-to-many relations that are specified using related name from kwargs
for field in baker.model._meta.get_fields():
if field.many_to_many and hasattr(field, "related_model"):
reverse_relation_name = (
field.related_query_name
or field.related_name
or f"{field.related_model._meta.model_name}_set"
)
if reverse_relation_name in kwargs:
getattr(entry, reverse_relation_name).set(
kwargs[reverse_relation_name]
)

return created_entries
15 changes: 14 additions & 1 deletion tests/test_baker.py
Original file line number Diff line number Diff line change
Expand Up @@ -1056,8 +1056,8 @@ def test_annotation_within_manager_get_queryset_are_run_on_make(self):
assert movie.title == movie.name


@pytest.mark.django_db
class TestCreateM2MWhenBulkCreate(TestCase):
@pytest.mark.django_db
def test_create(self):
query_count = 12
with self.assertNumQueries(query_count):
Expand All @@ -1068,6 +1068,19 @@ def test_create(self):
c1, c2 = models.Classroom.objects.all()[:2]
assert list(c1.students.all()) == list(c2.students.all()) == [person]

def test_make_should_create_objects_using_reverse_name(self):
classroom = baker.make(models.Classroom)

with self.assertNumQueries(21):
students = baker.make(
models.Person,
classroom_set=[classroom],
_quantity=10,
_bulk_create=True,
)

assert students[0].classroom_set.count() == 1


class TestBakerSeeded:
@pytest.fixture()
Expand Down

0 comments on commit 6784e68

Please sign in to comment.