Some objects expect additional method calls or complex processing for proper definition. For instance, a User may need to have a related Profile, where the Profile is built from the User object.
A post-generation hook will be defined with a given attribute name. When calling the Factory, some arguments will be passed to the post-generation hook instead of being available for Factory building:
- An argument with the same name as the post-generation hook attribute will be passed to the hook
- All arguments beginning with that name and __ will be passed to the hook, after removing the prefix.
Example:
class MyFactory(factory.Factory):
blah = factory.PostGeneration(lambda obj, create, extracted, **kwargs: 42)
MyFactory(
blah=42, # Passed in the 'extracted' argument of the lambda
blah__foo=1, # Passed in kwargs as 'foo': 1
blah__baz=2, # Passed in kwargs as 'baz': 2
blah_bar=3, # Not passed
)
The prefix used for extraction can be changed by setting the extract_prefix argument of the hook:
class MyFactory(factory.Factory):
@factory.post_generation(extract_prefix='bar')
def foo(self, create, extracted, **kwargs):
self.foo = extracted
MyFactory(
bar=42, # Will be passed to 'extracted'
bar__baz=13, # Will be passed as 'baz': 13 in kwargs
foo=2, # Won't be passed to the post-generation hook
)