Skip to content

Commit

Permalink
Fix make_recipe to work with _quantity model-bakers#28
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasrcezimbra committed Jun 20, 2024
1 parent a9ae541 commit 023ece1
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
6 changes: 6 additions & 0 deletions model_bakery/baker.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,9 @@ def _handle_one_to_many(self, instance: Model, attrs: Dict[str, Any]):
for key, values in attrs.items():
manager = getattr(instance, key)

if callable(values):
values = values()

for value in values:
# Django will handle any operation to persist nested non-persisted FK because
# save doesn't do so and, thus, raises constraint errors. That's why save()
Expand All @@ -659,6 +662,9 @@ def _handle_one_to_many(self, instance: Model, attrs: Dict[str, Any]):

def _handle_m2m(self, instance: Model):
for key, values in self.m2m_dict.items():
if callable(values):
values = values()

for value in values:
if not value.pk:
value.save()
Expand Down
3 changes: 2 additions & 1 deletion model_bakery/recipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ def _mapping( # noqa: C901
else:
mapping[k] = v.recipe.prepare(_using=_using, **recipe_attrs)
elif isinstance(v, related):
mapping[k] = v.make()
mapping[k] = v.make

mapping.update(new_attrs)
mapping.update(rel_fields_attrs)
return mapping
Expand Down
5 changes: 5 additions & 0 deletions tests/test_recipes.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,11 @@ def test_related_models_recipes(self):
assert lady.dog_set.all()[0].breed == "Pug"
assert lady.dog_set.all()[1].breed == "Basset"

def test_related_models_recipes_make_mutiple(self):
ladies = baker.make_recipe("tests.generic.dog_lady", _quantity=2)
assert ladies[0].dog_set.count() == 2
assert ladies[1].dog_set.count() == 2

def test_nullable_related(self):
nullable = baker.make_recipe("tests.generic.nullable_related")
assert nullable.dummynullfieldsmodel_set.count() == 1
Expand Down

0 comments on commit 023ece1

Please sign in to comment.