model-bakers / model_bakery

Object factory for Django
https://model-bakery.readthedocs.io/en/latest/
Other
833 stars 85 forks source link

Using make_recipe with _quantity together with related key only applies to last item created #28

Closed urbnjamesmi1 closed 3 months ago

urbnjamesmi1 commented 5 years ago

Using make_recipe with _quantity together with related key only applies to last item created

Given this setup code:

mommy_recipes.py:

dog1 = recipe.Recipe(
     Dog
)

dog2 = recipe.Recipe(
    Dog
)

company = recipe.Recipe(
    Company
)

incomplete_person = recipe.Recipe(
    Person,
    dog_set=recipe.related(dog1, dog2)
)

complete_person = incomplete_person.extend(
    company=recipe.foreign_key(company)
)

In a test python file:

people = mommy.make_recipe("complete_person", _quantity=3)

Expected behavior

That each model in people has the 2 dog instances.

Actual behavior

Only the last item in people has the 2 dog instances. The first 2 are empty.

Reproduction Steps

How to reproduce this issue.

See summary above

Versions

Python: 3.6 Django: 1.9 Model Mommy: 1.6.0

urbnjamesmi1 commented 5 years ago

I was able to work around this by calling mommy.make_recipe("complete_person") in a list comprehension, but it's a bug if I use the _quantity keyword

danizen commented 5 years ago

Declaring a kwargs that holds the attrs that transcend one recipe seems a more flexible workaround.

# dog1, dog2, and company as above

person_kwargs={
    'dog_set': recipe.related(dog1, dog2)
)

unemployed_person = Recipe(Person,
    **person_kwargs
)

employed_person = Recipe(Person, 
    company=recipe.foreign_key(company)
    **person_kwargs
)

NOTE: I also reject the notion that you need a company to be complete ;).

urbnjamesmi1 commented 5 years ago

Then extend doesn't truly extend in all cases. You have to explicitly remember these type of arguments and explicitly specify them each time? That should at least be documented, but it would be nice to have it fixed.

danizen commented 5 years ago

@urbnjamesmi1, yes it is a bug that should be fixed, but wanted to share a possibly useful workaround.

amureki commented 3 months ago

Released in 1.18.2, thanks to @lucasrcezimbra ! 🎉