Factory Boy弃用了set_creation_function(参见ChangeLog 2.6.1)并建议开发人员
使用SomeFactory的_create()方法的替换替换factory.set_creation_function(SomeFactory,creation_function)
我有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
alecxe.. 5
样本无法工作代码的两个主要问题:
该类应该来自SQLAlchemyModelFactory
类
该_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()
方法.
样本无法工作代码的两个主要问题:
该类应该来自SQLAlchemyModelFactory
类
该_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()
方法.