简体   繁体   English

sqlalchemy:不同表的基数相同

[英]sqlalchemy: Same Base for different tables

I have different tables, that I declare in a very standard way, but with a global Base:我有不同的表,我以非常标准的方式声明,但具有全局基础:

GlobalData.py全球数据.py

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

init()
engine= ...
Base.metadata.create_all(engine)

TableA.py表A.py

import globaldata as gd
TableA(gd.Base)
...

TableB.py表B.py

import globaldata as gd
TableB(gd.Base)
...

Problem: If I import TableA or to TableB more than once in other files, the tables will be added more than once in the metadata.问题:如果我在其他文件中多次导入 TableA 或 TableB,则表将在元数据中多次添加。 Then this created conflict when I try any action on one of those tables.然后,当我在其中一张表上尝试任何操作时,就会产生冲突。


EDIT编辑

The issue I receive, when I try to access a table is:当我尝试访问表时收到的问题是:

Multiple classes found for path "RolloutPermission" in the registry of this declarative base.在此声明性基础的注册表中找到路径“RolloutPermission”的多个类。 Please use a fully module-qualified path.请使用完全模块限定的路径。

I assume this is a design issue, however, I don't see what is wrong with mine.我认为这是一个设计问题,但是,我看不出我有什么问题。 Any input is welcomed欢迎任何输入

I also kind of did the same as you did, sort of.我也做了和你一样的事情,有点。 I only declare the base and import it everywhere, like you do, but without this code我只声明基础并在任何地方导入它,就像你一样,但没有这个代码

init()   

engine=Base.metadata.create_all(engine)

I import my base then in an env file from alembic and generate migrations.我将我的基础导入到 alembic 的 env 文件中并生成迁移。 If you're going to work with a slightly more complex I highly recommand migration files:).如果您要使用稍微复杂一点的工作,我强烈推荐迁移文件:)。

The problem might indeed be that you basically call create_all on every import.问题可能确实是您基本上在每次导入时都调用 create_all 。 Look into alembic, get rid of the few lines I wrote above and you'll have working code:)看看 alembic,去掉我上面写的几行,你就会有工作代码:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM