Django和Postgresql模式 [英] Django and postgresql schemas

查看:189
本文介绍了Django和Postgresql模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力解决这个问题,非常感谢。



我在postgres db中有各种模式,我希望能够可以从相同或不同的django应用程序内部映射到它们。



其中一些模式是:



样本



发掘



地球物理学





我尝试了推荐的方法,但是我没有从架构中显示任何数据,我只能通过托管表连接到公共架构。这是来自settings.py文件的数据库连接。

  DATABASES = {

'default' :{{
'ENGINE':'django.db.backends.postgresql_psycopg2',
'OPTIONS':{
'options':'-c search_path = django,public'
},
'NAME':'gygaia',
'USER':'appuser',
'PASSWORD':'secret',
},

'samples':{
'ENGINE':'django.db.backends.postgresql_psycopg2',
'OPTIONS':{
'options':'-c search_path = samples,public '
},
'NAME':'gygaia',
'USER':'appuser',
'PASSWORD':'secret',
},
}

来源: https://www.amvtek.com/blog/posts/2014/Jun/13/accessing -multiple-postgres-schemas-from-django /



在模型中添加:

 从django.db导入模型

#在此处创建模型。
class Storage(models.Model):
#id = models.IntegerField(默认= 0)
storage_id = models.AutoField(primary_key = True)
store_name = models.CharField (max_length = 200,default ='')
address_1 = models.CharField(max_length = 200,default ='')
address_2 = models.CharField(max_length = 200,default ='')
region = models.CharField(max_length = 200,default ='')
city = models.CharField(max_length = 200,default ='')
zip = models.CharField(max_length = 200, default ='')
国家= models.CharField(max_length = 200,default = Turkey)
user = models.CharField(max_length = 200,default = Gygaia)
datetamp = models.DateTimeField(auto_now = True)

class Meta():
managed = False
db_table ='samples\ .\ store'

我不想将模式限制为用户,并且数据库是几年前创建的,所以我不是所有希望将所有内容都放在一种模式下。我知道有很多解决方案都发布在stackoverflow和其他Internet核心上,我已经尝试过了,但是我无法使其正常工作。

解决方案

,因为Django不支持现成的Postgres数据库架构,所以有什么想法吗?

解决方案

要使其正常工作,请使用数据库路由器



我创建了一个测试数据库来进行尝试,下面是重现它的方法:



创建一个测试带有psql的数据库:

 用密码'lol so easy'创建用户测试器; 
使用OWNER测试器创建数据库multi_schema_db;
创建模式样本授权测试仪;
创建表samples.my_samples(
id INTEGER NOT NULL PRIMARY KEY,
description CHAR(255)NOT NULL
);

将架构添加到设置中作为不同的数据库连接,请记住添加 HOST 以避免对等身份验证失败错误。

  DATABASES = {

'default':{
'ENGINE':'django.db.backends.postgresql_psycopg2',
'OPTIONS':{
'options':'-c search_path = django,public '
},
'NAME':'multi_schema_db',
'USER':'tester',
'PASSWORD':'lol so easy',
' HOST':'localhost'

},

'samples':{
'ENGINE':'django.db.backends.postgresql_psycopg2',
'选项':{
'选项':'-c search_path = samples,public'
},
'NAME':'multi_schema_db',
'USER':'测试人员,
'PASSWORD':'大声这么简单',
'HOST':'localhost'
},

}



下一步,创建 MySample 模型:

 从django.db导入models 

class MySample(models.Model):
description = models.CharField(max_length = 255,null = False)

class Meta:
managed = False
db_table ='my_samples'

创建一个数据库路由器来引导所有样本-对示例数据库的相关查询:

  from database_test.models import MySample 

ROUTED_MODELS = [MySample]


class MyDBRouter(object):

def db_for_read(self,model,** hints):
如果模型在ROUTED_MODELS中:
return'samples'
return None

def db_for_write(self,model,** hints):
如果模型在ROUTED_MODELS中:
return'samples'
return None

基本上,路由器会将ROUTED_MODELS中指定的所有模型路由到数据库连接 samples 并为所有其他模型返回None。这会将它们路由到默认数据库连接。



最后将路由器添加到您的设置中。py

  DATABASE_ROUTERS =('database_test.db_router.MyDBRouter',)

现在,当查询 MySample 模型时,它将从 samples中获取数据模式。


I've been trying to solve this one all week, help very much appreciated.

I have various schemas in a postgres db and I would like to be able to map to them from within the same or across different django apps.

Some of the schemas are :

samples

excavation

geophysics

...

I have tried the recommended way, but I'm not getting any data to display from the schemas, I can only connect to the public schema with managed tables. Here is the database connections from the settings.py file.

DATABASES = {

'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'OPTIONS': {
            'options': '-c search_path=django,public'
        },
        'NAME': 'gygaia',
        'USER': 'appuser',
        'PASSWORD': 'secret',
},

'samples': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'OPTIONS': {
            'options': '-c search_path=samples,public'
        },
        'NAME': 'gygaia',
        'USER': 'appuser',
        'PASSWORD': 'secret',
},
}

source: https://www.amvtek.com/blog/posts/2014/Jun/13/accessing-multiple-postgres-schemas-from-django/

In the model.py I add:

    from django.db import models

    # Create your models here.
    class Storage(models.Model):
        #id = models.IntegerField(default=0)
        storage_id = models.AutoField(primary_key=True)
        store_name = models.CharField(max_length=200, default='')
        address_1 = models.CharField(max_length=200, default='')
        address_2 = models.CharField(max_length=200, default='')
        region = models.CharField(max_length=200, default='')
        city = models.CharField(max_length=200, default='')
        zip = models.CharField(max_length=200, default='')
        country = models.CharField(max_length=200, default="Turkey")
        user = models.CharField(max_length=200, default="Gygaia")
        datestamp = models.DateTimeField(auto_now=True)

    class Meta():
        managed=False
        db_table = 'samples\".\"store'

I don't want to restrict schemas to users, and the database was created a few years ago so I'm not allowed to bring it all under one schema. I know there are various solutions posted on stackoverflow and other coreners of the internet, I have tried these, but I'm unable to get this to work. Any ideas how to solve thos one??

解决方案

Because Django does not support Postgres database schemas out of the box, in order to get this to work, use a database router.

I created a test database to try this out with, here's how to reproduce it:

Create a test database with psql:

CREATE USER tester WITH PASSWORD 'lol so easy';
CREATE DATABASE multi_schema_db WITH OWNER tester;
CREATE SCHEMA samples AUTHORIZATION tester;
CREATE TABLE samples.my_samples (
  id          INTEGER   NOT NULL PRIMARY KEY,
  description CHAR(255) NOT NULL
);

Add the schemas to the settings as different database connections, remember to add HOST to avoid the "Peer authentication failed" error.

DATABASES = {

'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'OPTIONS': {
        'options': '-c search_path=django,public'
    },
    'NAME': 'multi_schema_db',
    'USER': 'tester',
    'PASSWORD': 'lol so easy',
    'HOST': 'localhost'

},

'samples': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'OPTIONS': {
        'options': '-c search_path=samples,public'
    },
    'NAME': 'multi_schema_db',
    'USER': 'tester',
    'PASSWORD': 'lol so easy',
    'HOST': 'localhost'
},

}

Next create the MySample model:

from django.db import models

class MySample(models.Model):
    description = models.CharField(max_length=255, null=False)

    class Meta:
        managed = False
        db_table = 'my_samples'

Create a database router to direct all sample-related queries to the sample database:

from database_test.models import MySample

ROUTED_MODELS = [MySample]


class MyDBRouter(object):

    def db_for_read(self, model, **hints):
        if model in ROUTED_MODELS:
            return 'samples'
        return None

    def db_for_write(self, model, **hints):
        if model in ROUTED_MODELS:
            return 'samples'
        return None

Basically, the router will route all the models specified in ROUTED_MODELS to the database connection samples and return None for all the other models. This will route them to the default database connection.

Finally add the router to your settings.py

DATABASE_ROUTERS = ('database_test.db_router.MyDBRouter',)

And now when doing a query for the MySample model, it will fetch data from the samples schema.

这篇关于Django和Postgresql模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆