说我有一个带有const myClass = require('../index');
const myService = require('../myService');
describe('service-tests - index', () => {
let doOtherStuffMock;
beforeAll(() => {
doOtherStuffMock = jest.spyOn(myService.prototype, 'doOtherStuff');
});
it('mocks doOtherStuff one way', async () => {
doOtherStuffMock.mockResolvedValue('I am a mocked value');
const result = await myClass.doStuff((err, data) => data);
expect(result).toBe("I am a mocked value");
});
it('mocks doOtherStuff another way', async () => {
doOtherStuffMock.mockResolvedValue('I am DIFFERENT mocked value');
const result = await myClass.doStuff((err, data) => data);
expect(result).toBe('I am DIFFERENT mocked value');
});
});
和schema1
的Postgres数据库。我希望我的Django应用程序schema2
可以同时访问myapp
和schema1
中的数据。
我几乎找到了一种使用schema2
(基于this answer的解决方法),直到我意识到这破坏了Django admin,并因此破坏了其他功能。
我试图在模型的app_labels
中指定自定义app_label
:
Meta
然后,我为myapp实现了两个单独的路由器,每个路由器都路由到以下一种模式:
class OneModel(models.Model):
gid = models.AutoField(primary_key=True)
name = models.CharField(max_length=40, blank=True, null=True)
class Meta:
managed = False
db_table = 'one_table'
app_label = 'myapp_to_schema1'
class AnotherModel(models.Model):
gid = models.AutoField(primary_key=True)
color = models.CharField(max_length=40, blank=True, null=True)
class Meta:
managed = False
db_table = 'another_table'
app_label = 'myapp_to_schema2'
最后,数据库的设置如下:
class MyappToSchema1Router:
def db_for_read(self, model, **hints):
if model._meta.app_label == 'myapp_to_schema1':
return 'schema1'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == 'myapp_to_schema1':
return 'schema1'
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label == 'myapp_to_schema1':
return db == 'schema1'
return None
class MyappToSchema2Router:
def db_for_read(self, model, **hints):
if model._meta.app_label == 'myapp_to_schema2':
return 'schema2'
return None
def db_for_write(self, model, **hints):
if model._meta.app_label == 'myapp_to_schema2':
return 'schema2'
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label == 'myapp_to_schema2':
return db == 'schema2'
return None
如前所述,这很好用(即我可以使用DATABASES = {
'default':
{
},
'schema1':
{
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'OPTIONS': {
'options': '-c search_path=schema1'
},
'NAME': 'mydb',
'USER': secrets.USER,
'PASSWORD': secrets.PASSWORD,
'HOST': 'my.host.address',
'PORT': '5432',
},
'schema2':
{
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'OPTIONS': {
'options': '-c search_path=schema2'
},
'NAME': 'mydb',
'USER': secrets.USER,
'PASSWORD': secrets.PASSWORD,
'HOST': 'my.host.address',
'PORT': '5432',
},
}
}
和OneModel.objects.all()
在Python shell中访问两个模型),但是当访问Django管理员时,出现错误{{1} }
从单个应用程序访问多个架构的正确方法是什么?