Factory Boy已弃用set_creation_function(请参阅ChangeLog 2.6.1)并建议开发人员
替换factory.set_creation_function(SomeFactory,creation_function) 覆盖SomeFactory
的_create()方法
我有i)许多衍生工厂类和ii)我的数据库会话在另一个模块中实例化,因此我尝试用https://github.com/mattupstate/overholt替换下面第二个代码块的工作示例。 PyCharm警告我没有使用“db”导入,所以我怀疑在设置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
答案 0 :(得分:5)
示例无效代码的两个主要问题:
SQLAlchemyModelFactory
class _create()
方法应定义为classmethod
修正版:
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
以下是覆盖_create()
方法的模型工厂的sample。