In defining a ModelFactory in FactoryBoy, I need to access an attribute of another model created by SubFactory and assign it to this ModelFactory's attribute.
This is what I want to do:
import factory
class MyModelFactory(factory.DjangoModelFactory):
FACTORY_FOR = MyModel
created_by = factory.SubFactory(AdminUserFactory)**.id**
Obviously that doesn't work because there is no AdminUser object to access the id in the MyModelFactory class definition.
This is what I have done, but it is ugly:
import factory
class MyModelFactory(factory.DjangoModelFactory):
FACTORY_FOR = MyModel
dummy_created_by = factory.SubFactory(AdminUserFactory)
created_by = factory.LazyAttribute(lambda o: o.dummy_created_by.id)
@classmethod
def _create(cls, target_class, *args, **kwargs):
del kwargs['dummy_created_by']
return super(MyModelFactory, cls)._created(
target_class, *args, **kwargs)
I was trying to read through the Factory_Boy docs but didn't see a class or function that would allow me to lazily access the attribute. Does Anyone have any suggestions?