Factory Boy deprecated set_creation_function (see ChangeLog 2.6.1) and recommends that developers
Replace factory.set_creation_function(SomeFactory, creation_function) with an override of the _create() method of SomeFactory
I have i) a number of derivative factory classes and ii) my db session instantiated in another module so I tried replacing the working example from https://github.com/mattupstate/overholt with the second code block below. PyCharm is warning me that the "db" import is not being used, so I suspect it might not be being dereferenced properly when I set sqlalchemy_session?
from myapp.core import db
def create_sqlalchemy_model_function(class_to_create, *args, **kwargs):
entity = class_to_create(**kwargs)
db.session.add(entity)
db.session.commit()
return entity
Factory.set_creation_function(create_sqlalchemy_model_function)
from factory.alchemy import SQLAlchemyModelFactory as Factory
from myapp.core import db
class Factory():
class Meta:
sqlalchemy_session = db.session
def _create(cls, model_class, *args, **kwargs):
entity = model_class(*args, **kwargs)
db.session.add(entity)
db.session.commit()
return entity
Two major issues with your sample not-working code:
SQLAlchemyModelFactory
class_create()
method should be defined as classmethod
Fixed version:
from factory.alchemy import SQLAlchemyModelFactory as Factory
from myapp.core import db
class MyFactory(Factory):
class Meta:
sqlalchemy_session = db.session
@classmethod
def _create(cls, model_class, *args, **kwargs):
entity = model_class(*args, **kwargs)
db.session.add(entity)
db.session.commit()
return entity
Here is also a sample of the model factory overriding the _create()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With