django - 为 TestCase 装置指定数据库

发布于 2024-09-30 13:06:50 字数 332 浏览 0 评论 0原文

我的网站使用两个数据库,并且我有一个使用这两个数据库的应用程序。我需要编写一个为两个数据库加载固定装置的测试用例。我使用数据库路由器,它在生产中运行良好,但在测试框架中,Django 坚持对所有装置使用“默认”数据库,即使对于指定其他数据库的模型也是如此。我如何告诉 Django 针对另一个数据库运行固定装置?

我的测试用例定义列表:

class VerifierTestCase(TestCase):
    fixtures = ['zipcodes_test.json', 'all_states.json', 'wtf.json']
    multi_db = True

I have two databases that my site uses and I have an app that uses both of them. I need to write a TestCase that loads fixtures for both databases. I use a DB router, which works fine in production, but in the testing framework, Django insists on using the 'default' database for all fixtures, even for models that specify the other database. How do I tell Django to run a fixture against another database?

My TestCase is defined list:

class VerifierTestCase(TestCase):
    fixtures = ['zipcodes_test.json', 'all_states.json', 'wtf.json']
    multi_db = True

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

回首观望 2024-10-07 13:06:51

实际上,Django 中有一个错误,如果您指定整个设备名称,它会导致它忽略基于名称的数据库特定指针。

所以如果你这样做 fixtures = ["mydata.default.yaml", "mydata.myotherdatabase.yaml"]

它将把两个装置加载到默认数据库中。

但如果你这样做 fixtures = ['mydata']

它将正确加载。对于 dbengine 特定的文件名(例如 mydata.default.postgresql.sql)也是如此。

There is actually a bug in Django that causes it to ignore the name-based db-specific pointers if you specify the entire fixture name.

so if you do fixtures = ["mydata.default.yaml", "mydata.myotherdatabase.yaml"]

It will load both fixtures into the default database.

But if you do fixtures = ['mydata']

It will load correctly. This is also true for dbengine specific filenames (e.g. mydata.default.postgresql.sql) as well.

地狱即天堂 2024-10-07 13:06:51

夹具通过文件名针对特定数据库。在 TestCase 实例中也是如此,因为它们只是调用 loaddata 命令。

请参阅 https://docs.djangoproject.com/en /dev/ref/django-admin/#database-specific-fixtures

Fixtures are targeted at specific databases by filename. This is true in TestCase instances as well, as they just call the loaddata command.

See https://docs.djangoproject.com/en/dev/ref/django-admin/#database-specific-fixtures

桃扇骨 2024-10-07 13:06:51

如果您有一个多数据库设置,其中模型专用于每个数据库。您需要为每个数据库保存一个fixture文件(不适用的数据库文件为空)。

如果您的代码定义了 fixtures = ["sample"] 并且您有两个数据库 defaultother

您需要两个文件:sample.default.jsonsample.other.json。如果 sample 仅包含数据库 default 中的模型,则 sample.other.json 将是一个空文件 ([] ),反之亦然。

尝试过Django 3.2

If you have a multi-db setup with models exclusive to each database. You need to save a fixture file for each database (with the non-applicable database files being empty).

If your code defines fixtures = ["sample"] and you have two databases default and other.

You need two files: sample.default.json and sample.other.json. If sample contains only models from db default, sample.other.json will be an empty file ([]) and vice-versa.

Tried with Django 3.2

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文