Skip to content

Commit

Permalink
Fix issue and add test coverage (model-bakers#385)
Browse files Browse the repository at this point in the history
  • Loading branch information
magdumsuraj07 committed Nov 14, 2023
1 parent 38d2dd7 commit 3ad58ec
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
14 changes: 14 additions & 0 deletions model_bakery/baker.py
Expand Up @@ -841,4 +841,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
8 changes: 8 additions & 0 deletions tests/generic/models.py
Expand Up @@ -478,3 +478,11 @@ class ModelWithAutoNowFields(models.Model):
sent_date = models.DateTimeField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)


class House(models.Model):
pass


class HouseDetail(models.Model):
houses = models.ManyToManyField(House, blank=True)
9 changes: 8 additions & 1 deletion tests/test_baker.py
Expand Up @@ -1039,8 +1039,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 = 13 if DJANGO_VERSION >= (4, 0) else 14
with self.assertNumQueries(query_count):
Expand All @@ -1051,6 +1051,13 @@ 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):
detail = baker.make(models.HouseDetail)
houses = baker.make(
models.House, housedetail_set=[detail], _quantity=20, _bulk_create=True
)
assert houses[0].housedetail_set.count() == 1


class TestBakerSeeded:
@pytest.fixture()
Expand Down

0 comments on commit 3ad58ec

Please sign in to comment.