You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Occasionally I want to have a SubFactory (or a RelatedFactory) whose value is set to None unless explicitly stated. That is, I would want to FooFactory().bar to be None but still be able to use FooFactory(bar__name='test) or FooFactory(bar=BarFactory()).
class BarFactory(DjangoModelFactory):
name = factory.Faker("first_name")
class FooFactory(DjangoModelFactory):
bar = factory.SubFactory(BarFactory)
Is this achievable somehow? Obviously I could use FooFactory(bar=None) but this is not ideal.
The text was updated successfully, but these errors were encountered:
aleehedl
changed the title
RelatedFactory with a None value by default
SubFactory with a None value by default
Jan 3, 2022
It's quite hard to support directly: in the current engine, declarations will be grouped by their "root", e.g all declarations starting with bar__ are considered to be parameters for the bar= declaration.
If the default is bar=None, any value provided to bar__name would either cause a failure or be ignored.
The simplest option would be to use a factory.Trait:
>>>FooFactory() # Nothing requested<Foo, bar=None>>>>FooFactory(with_bar=True) # Default call to `BarFactory`<Foo, bar=<Bar, name="John">>>>>FooFactory(with_bar=True, bar__name="test") # Include `bar=`, and provide a value<Foo, bar=<Bar, name="test">>>>>FooFactory(bar__name="test") # Slightly weird behaviour: the `BarFactory` is fully ignored.<Foo, bar=None>Ihopethishelps?
The problem
Occasionally I want to have a SubFactory (or a RelatedFactory) whose value is set to None unless explicitly stated. That is, I would want to
FooFactory().bar
to be None but still be able to useFooFactory(bar__name='test)
orFooFactory(bar=BarFactory())
.Is this achievable somehow? Obviously I could use
FooFactory(bar=None)
but this is not ideal.The text was updated successfully, but these errors were encountered: