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

Fix make_recipe to work with _quantity #28 #480

Merged
merged 2 commits into from
Jun 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
- Fix `make_recipe` to work with `_quantity` (#28)

### Removed

Expand Down
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
Loading