gpt4 book ai didi

python - SQLAlchemy - 创建表模板

转载 作者:太空宇宙 更新时间:2023-11-03 11:56:45 36 4
gpt4 key购买 nike

我刚开始使用 SQLAlchemy,我一直在想……我的模型中将有很多表。我希望我的模型中的每个表都有自己的文件。

我目前正在使用以下代码:

from sqlalchemy import MetaData
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects import postgresql
import sqlalchemy as sa

__all__ = ['Session', 'engine', 'metadata']

# SQLAlchemy database engine. Updated by model.init_model()
engine = None

# SQLAlchemy session manager. Updated by model.init_model()
Session = scoped_session(sessionmaker())

# Global metadata. If you have multiple databases with overlapping table
# names, you'll need a metadata for each database
metadata = MetaData()

# declarative table definitions
Base = declarative_base()
Base.metadata = metadata

schema = 'srbam_dev'

在 meta.py 中

_init_.py 中跟随

"""The application's model objects"""
import sqlalchemy as sa
from sqlalchemy import orm

from models import meta
from models.filers import Filer
from models.vfilers import Vfiler
from models.filer_options import FilerOption

def init_models(engine):
"""Call me before using any of the tables or classes in the model"""
## Reflected tables must be defined and mapped here
#global reflected_table
#reflected_table = sa.Table("Reflected", meta.metadata, autoload=True,
# autoload_with=engine)
#orm.mapper(Reflected, reflected_table)
#
meta.engine = sa.create_engine(engine)
meta.Session.configure(bind=meta.engine)

class Basic_Table(object):
id = sa.Column(
postgresql.UUID(),
nullable=False,
primary_key=True
)
created = sa.Column(
sa.types.DateTime(True),
nullable=False
)
modified = sa.Column(
sa.types.DateTime(True),
nullable=False
)

然后关注我所有的模型

from models.meta import Base
from models.meta import Basic_Table
from models.meta import schema
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

class Filer(Base,Basic_Table):

这很好用,只要我不开始在表上使用一些外键,一旦我使用外键就说

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 't_vfilers.filer_id' could not find table 't_filers' with which to generate a foreign key to target column 'id'

我尝试直接在 Filer 类中定义 id 键(并从声明中删除 Basic_Table),但这并没有解决问题。

我创建数据库的代码如下所示 #!/usr/bin/python 导入配置解析器 从 sqlalchemy.engine.url 导入 URL 从模型导入 *

config = ConfigParser.RawConfigParser()
config.read('conf/core.conf')
db_url = URL(
'postgresql+psycopg2',
config.get('database','username'),
config.get('database','password'),
config.get('database','host'),
config.get('database','port'),
config.get('database','dbname')
)

init_models(db_url)
meta.Base.metadata.drop_all(bind=meta.engine)
meta.Base.metadata.create_all(bind=meta.engine)

有人知道如何解决这个问题吗?

最佳答案

Marek,做一件事尝试定义外键和架构名称,即“test.t_vfilers.filer_id”(此处“test”是架构名称),这将解决问题。

关于python - SQLAlchemy - 创建表模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6803072/

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