From 2a3564f7261c928b1f3a2e52baccb68ea7926e88 Mon Sep 17 00:00:00 2001 From: MaHryCT3 <96225040+MaHryCT3@users.noreply.github.com> Date: Sun, 5 Jan 2025 20:07:59 +0500 Subject: [PATCH] Fix `Recipe.prepare` without `_quantity` (on one-to-one relation) (#512) Co-authored-by: velizhanin_ie --- model_bakery/recipe.py | 4 +++- tests/test_baker.py | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/model_bakery/recipe.py b/model_bakery/recipe.py index d2f11e7e..316e50fd 100644 --- a/model_bakery/recipe.py +++ b/model_bakery/recipe.py @@ -164,9 +164,11 @@ def prepare( **attrs: Any, ) -> Union[M, List[M]]: defaults = { - "_quantity": _quantity, "_save_related": _save_related, } + if _quantity is not None: + defaults["_quantity"] = _quantity # type: ignore[assignment] + defaults.update(attrs) return baker.prepare( self._model, _using=_using, **self._mapping(_using, defaults) diff --git a/tests/test_baker.py b/tests/test_baker.py index 46c26c44..49180994 100644 --- a/tests/test_baker.py +++ b/tests/test_baker.py @@ -20,7 +20,9 @@ ) from model_bakery.timezone import tz_aware from tests.generic import models +from tests.generic.baker_recipes import lonely_person from tests.generic.forms import DummyGenericIPAddressFieldForm +from tests.generic import baker_recipes def test_import_seq_from_baker(): @@ -286,6 +288,12 @@ def test_create_one_to_one(self): assert lonely_person.pk is None assert lonely_person.only_friend.pk + def test_recipe_prepare_model_with_one_to_one_and_save_related(self): + lonely_person = baker_recipes.lonely_person.prepare(_save_related=True) + + assert lonely_person.pk is None + assert lonely_person.only_friend.pk + @pytest.mark.django_db class TestBakerCreatesAssociatedModels(TestCase):