Skip to content

Commit 6784e68

Browse files
Fix #385 -- Handle bulk creation when using reverse related name (#486)
* Fix issue and add test coverage (#385) * Reuse existing test models, check the query count --------- Co-authored-by: Suraj Magdum <[email protected]>
1 parent 5aa3070 commit 6784e68

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
1010
### Added
1111

1212
### Changed
13+
- Handle bulk creation when using reverse related name
1314

1415
### Removed
1516

model_bakery/baker.py

+14
Original file line numberDiff line numberDiff line change
@@ -864,4 +864,18 @@ def bulk_create(baker: Baker[M], quantity: int, **kwargs) -> List[M]:
864864
for obj in kwargs[field.name]
865865
]
866866
)
867+
868+
# set many-to-many relations that are specified using related name from kwargs
869+
for field in baker.model._meta.get_fields():
870+
if field.many_to_many and hasattr(field, "related_model"):
871+
reverse_relation_name = (
872+
field.related_query_name
873+
or field.related_name
874+
or f"{field.related_model._meta.model_name}_set"
875+
)
876+
if reverse_relation_name in kwargs:
877+
getattr(entry, reverse_relation_name).set(
878+
kwargs[reverse_relation_name]
879+
)
880+
867881
return created_entries

tests/test_baker.py

+14-1
Original file line numberDiff line numberDiff line change
@@ -1056,8 +1056,8 @@ def test_annotation_within_manager_get_queryset_are_run_on_make(self):
10561056
assert movie.title == movie.name
10571057

10581058

1059+
@pytest.mark.django_db
10591060
class TestCreateM2MWhenBulkCreate(TestCase):
1060-
@pytest.mark.django_db
10611061
def test_create(self):
10621062
query_count = 12
10631063
with self.assertNumQueries(query_count):
@@ -1068,6 +1068,19 @@ def test_create(self):
10681068
c1, c2 = models.Classroom.objects.all()[:2]
10691069
assert list(c1.students.all()) == list(c2.students.all()) == [person]
10701070

1071+
def test_make_should_create_objects_using_reverse_name(self):
1072+
classroom = baker.make(models.Classroom)
1073+
1074+
with self.assertNumQueries(21):
1075+
students = baker.make(
1076+
models.Person,
1077+
classroom_set=[classroom],
1078+
_quantity=10,
1079+
_bulk_create=True,
1080+
)
1081+
1082+
assert students[0].classroom_set.count() == 1
1083+
10711084

10721085
class TestBakerSeeded:
10731086
@pytest.fixture()

0 commit comments

Comments
 (0)