gpt4 book ai didi

django - Django:多个数据库,路由器和测试框架

转载 作者:行者123 更新时间:2023-12-03 19:01:01 27 4
gpt4 key购买 nike

我目前正在为django应用程序编写测试。
遗憾的是,我们不得不使用多个数据库布局,无法更改此布局。 (跨多个数据中心的不同服务器上具有多个后端的分布式数据库)

我们有两个数据库:


带有Django默认表的默认数据库
一些模型的应用程序数据库


对于这些模型,我们编写了不同的路由器,如django网站上记录的那样。
现在的问题是,如果我运行python manage.py test customerreceipips,则测试框架会在几秒钟后死于以下错误:

django.db.utils.ProgrammingError: relation "auth_user" does not exist


我检查了创建的数据库,没有表。因此,来自模型的查询将引发错误。

问题模型是(在数据库2中):

class CustomerReceipts(models.Model):

def _choices_user():
users = User.objects.all()
users = users.order_by('id')
return [(e.id, e.username) for e in users]

# General
receipt_name = models.CharField(max_length=20, verbose_name="Receipt name") #: Receipt name
....

# Auditing
owner = models.IntegerField(verbose_name="Owner", choices=[('', '')] + _choices_user())


因为多个数据库设置不支持直接链接,所以我们为所有者使用IntegerField,并且业务逻辑处理完整性。

问题是_choices_user()可以为丢失的表设置查询。我不明白的是,为什么django在第一次运行时不创建表auth_user。如果我删除带有原因模型的应用程序,则测试框架可以正常工作。

有什么想法可以解决吗?

谢谢!

编辑:
我创建了一个数据库设置,并尝试了相同的操作。可悲的是它抛出了同样的错误!
我现在很困惑。有人也可以测试吗?使用_choices_user方法创建模型并运行测试。

最佳答案

您可以手动选择数据库。只需调用using()。 using()方法采用一个参数:要在其上运行查询的数据库的别名。

def _choices_user():
users = User.objects.using('default').all()
.....
.....


Django 1.7 docs

关于django - Django:多个数据库,路由器和测试框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24290179/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com