model-bakers / model_bakery

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

Recipe post creation callback #25

Open HeyHugo opened 5 years ago

HeyHugo commented 5 years ago

Hi!

I'd like to hear if this is a feature that if not already possible somehow would be something worth considering. My use case is that I have models that are only ever sensible if they have a couple of related models, so creating these by hand after the main model feels cumbersome.

I know I can reference other recipes with recipe.foreign_key() and recipe.related() but these don't always help when for example two relations of a model are also related to each other.

What I'm after is a callback for a recipe that would run just after the recipe created the object, and then the object could be used within this callback to for example create related objects.

I guess what I'm after is something similar to factory boys PostGeneration / PostGenerationMethod but for model mommy recipes.

berinhard commented 4 years ago

Hey @amureki and @anapaulagomes I'd like to hear your thoughts on this one too.

I loved the suggestion and I wasn't familiar with Factory Boy's API. I think we can add this not only to our Recipes but also to baker.make and baker.prepare as well. Do you have any API suggestion?

ashiazed commented 3 years ago

Marshmallow has really nice pre/post hooks too, could be used for inspiration.

boatcoder commented 3 years ago

Could a simple solution be just post_create(baker.make(......))

I've got a similar problem to this one in that the profile of an user needs to be a certain way, but the user is the model that is the FK. Reading this problem description made me think of a way I could have done this more easily.