diff --git a/README.rst b/README.rst index 5e26406..2020c39 100644 --- a/README.rst +++ b/README.rst @@ -113,6 +113,41 @@ Sub-factory attribute points to the model fixture of the sub-factory. Attributes of sub-factories are injected as dependencies to the model fixture and can be overridden_ via the parametrization. +Django Model SubFactory with a custom fixture name +-------------------------------------------------- + +By default, the subfactory is retrieved by using the lowercase-underscore form of the Django model class name +and invoking that fixture from the pytest request. +If you want to use a different name, you must define it in the factory class Meta and use a custom DjangoModelFactory + +.. code-block:: python + + from factory.django import DjangoModelFactory, DjangoOptions + + class CustomFixtureFactoryOptions(DjangoOptions): + """Allow overriding the fixture name when referencing the factory via SubFactory/RelatedFactory.""" + def _build_default_options(self): + return super()._build_default_options() + [ + factory.base.OptionDefault("fixture_name", None), + ] + + + class CustomFixtureDjangoModelFactory(DjangoModelFactory): + _options_class = CustomFixtureFactoryOptions + + class Meta: + abstract = True + + + @register + class AuthorFactory(CustomFixtureDjangoModelFactory): + class Meta: + model = Author + fixture_name = "other_author" + + name = "Charles Dickens" + + Related Factory --------------- diff --git a/pytest_factoryboy/fixture.py b/pytest_factoryboy/fixture.py index 782806e..70764fe 100644 --- a/pytest_factoryboy/fixture.py +++ b/pytest_factoryboy/fixture.py @@ -273,6 +273,10 @@ def inject_into_caller(name: str, function: Callable[..., Any], locals_: Box[dic def get_model_name(factory_class: FactoryType) -> str: """Get model fixture name by factory.""" + overriden_fixture_name = getattr(factory_class._meta, "fixture_name", None) + if overriden_fixture_name is not None: + return overriden_fixture_name + model_cls = factory_class._meta.model if isinstance(model_cls, str): @@ -501,7 +505,7 @@ def attr_fixture(request: SubRequest, value: T) -> T: def subfactory_fixture(request: SubRequest, factory_class: FactoryType) -> Any: """SubFactory/RelatedFactory fixture implementation.""" - fixture = inflection.underscore(factory_class._meta.model.__name__) + fixture = inflection.underscore(get_model_name(factory_class)) return request.getfixturevalue(fixture)