我正在设置一个包含大量数据库的Django应用程序,其中一些使用相同的模型(它们不是复制品)。我已经配置了我的路由器,一切都很好。在进行测试时出现问题,因为我想使用factory-boy
。
在另一个项目中,我可以在Meta
内设置数据库但是现在,我必须选择在哪个数据库上动态创建一个实例(如果没有,我必须为每个创建一个DjangoModelFactory
数据库,这不会很漂亮。)
是否有(更简单的)方法为每次创建动态指定数据库?
答案 0 :(得分:1)
据我所知version <=2.10.0
(# factoryboy_utils.py
@classmethod
def _get_manager(cls, model_class):
return super(cls, cls)._get_manager(model_class).using(cls.database)
class DBAwareFactory(object):
"""
Context manager to make model factories db aware
Usage:
with DBAwareFactory(PersonFactory, 'db_qa') as personfactory_on_qa:
person_on_qa = personfactory_on_qa()
...
"""
def __init__(self, cls, db):
# Take a copy of the original cls
self.original_cls = cls
# Patch with needed bits for dynamic db support
setattr(cls, 'database', db)
setattr(cls, '_get_manager', _get_manager)
# save the patched class
self.patched_cls = cls
def __enter__(self):
return self.patched_cls
def __exit__(self, type, value, traceback):
return self.original_cls
)并没有提供类似的内容。
尽管如此,您的问题是使用上下文管理器的完美用例。它允许您在需要的地方动态设置数据库,并且只在期望的范围内,并且还可以干!:
from factoryboy_utils import DBAwareFactory
class MyTest(TestCase):
def test_mymodel_on_db1(self):
...
with DBAwareFactory(MyModelFactory, 'db1') as MyModelFactoryForDB1:
mymodelinstance_on_db1 = MyModelFactoryForDB1()
# whatever you need with that model instance
...
# something else here
def test_mymodel_on_db2(self):
...
with DBAwareFactory(MyModelFactory, 'db2') as MyModelFactoryForDB2:
mymodelinstance_on_db2 = MyModelFactoryForDB2()
# whatever you need with that model instance
...
# something else here
然后,在您的测试中,您可以执行以下操作:
String url = Information.URL_AllPosts + title;
URLEncoder.encode(url);
ShowPosts(url);