python – SQLAlchemy Automap backref错误

我是SQLAlchemy的新手(通常是ORM),我正在尝试将现有的应用程序移到SQLAlchemy上,以便我们可以将一些代码复杂性从当前存在的(和繁琐的更新)查询转移到
Python.不幸的是,我在数据库反射后立即收到错误.虽然我可以直接查询表,但我实际上并没有直接访问类或类之间的关系.下面是我想要做的几乎最小的例子.

现有的postgres表:

dev=> \d+ gmt_file
                                        Table "public.gmt_file"
  Column   |     Type     | Modifiers | Storage  | Stats target | Description 
-----------+--------------+-----------+----------+--------------+-------------
 file_id   | integer      | not null  | plain    |              |
       a   | integer      |           | plain    |              | 
       b   | integer      |           | plain    |              | 
Indexes:
    "gmt_file_pk" PRIMARY KEY, btree (file_id)
Foreign-key constraints:
    "gmt_file_a_fk" FOREIGN KEY (a) REFERENCES cmn_user(user_id)
    "gmt_file_b_fk" FOREIGN KEY (b) REFERENCES cmn_user(user_id)

SQLAlchemy应用程序(最小示例):

from sqlalchemy import create_engine
from sqlalchemy.orm import Session,Mapper
from sqlalchemy.ext.automap import automap_base

engine = create_engine('postgresql://user:pass@localhost:5432/dev')
Base = automap_base()
Base.prepare(engine, reflect=True)
session = Session(engine,autocommit=True)

session.query(Base.classes.gmt_file).all()

从目前为止我所知道的,这会引发backref错误,因为a和b都与不同表中的相同字段具有外键关系(这通常发生在现有数据库中).我尝试了多种处理此错误的方法,包括创建自定义命名函数(name_for_scalar_relationship()和name_for_collection_relationship()),但无济于事.在SQLAlchemy中,有没有一种标准的方法来处理这个问题,或者在反射期间禁用反射创建?

最终目标是以自动方式反映数据库,而不必为当前存在的数百个表编写自定义名称映射,但我不知道该怎么做.任何帮助表示赞赏.

谢谢

最佳答案 当多个外键引用同一列时,看起来我们使用automap获取属性名称冲突.

Base.prepare允许使用参数name_for_scalar_relationship和name_for_collection_relationship,它们使用用于生成属性名称的函数. (参见AutomapBase.prepare()name_for_collection_relationship()的文档)我能够通过定义自己的函数来解决backref错误.

修改你的最小例子:

from sqlalchemy import create_engine
from sqlalchemy.orm import Session,Mapper
from sqlalchemy.ext.automap import automap_base, name_for_collection_relationship

engine = create_engine('postgresql://user:pass@localhost:5432/dev')
Base = automap_base()

def _name_for_collection_relationship(base, local_cls, referred_cls, constraint):
    if constraint.name:
        return constraint.name.lower()
    # if this didn't work, revert to the default behavior
    return name_for_collection_relationship(base, local_cls, referred_cls, constraint)

Base.prepare(engine, reflect=True, name_for_collection_relationship=_name_for_collection_relationship)
session = Session(engine,autocommit=True)

session.query(Base.classes.gmt_file).all()

这应该有一个属性名为gmt_file_a_fk和gmt_file_b_fk的类.

这种方法对我有用.如果它不起作用,您也可以尝试类似地重新定义name_for_scalar_relationship().

如果要根据类重写,则必须确保正确定义列和关系.例如:

from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.orm import relationship

class GmtFile(Base):
    __tablename___ = 'gmt_file'

    file_id = Column('file_id', Integer, primary_key=True)

    a = Column('a', Integer, ForeignKey('CmnUser.user_id', name='gmt_file_a'))
    b = Column('b', Integer, ForeignKey('CmnUser.user_id', name='gmt_file_b'))
    # you'll need to define the class CmnUser as well

    # these variable names need to be the same as the ForeignKey names above
    gmt_file_a = relationship('CmnUser', foreign_keys=[a])
    gmt_file_b = relationship('CmnUser', foreign_keys=[b])
点赞