SQLAlchemy Automap backref错误

时间:2016-06-13 18:53:19

标签: python postgresql sqlalchemy

我是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()

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

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

谢谢

1 个答案:

答案 0 :(得分:1)

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

Base.prepare允许参数name_for_scalar_relationshipname_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_fkgmt_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])
相关问题