python - 只能使用关联表对象定义二级关系,不能使用名称

标签 python sqlalchemy

尝试在类 Note 和 Document 之间创建关联关系。我面临的问题是我的次要关系仅在我使用关联表对象而不是该表名时才有效。我的意思是关系:

notes = relationship(u'Note', secondary=t_Documented, backref='documents')

有效,但以下无效:

notes = relationship(u'Note', secondary='Documented', backref='documents')

查询时出现错误:

sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|Document|Document, expression 'Documented' failed to locate a name ("name 'Documented' is not defined"). If this is a class name, consider adding this relationship() to the class after both dependent classes have been defined.

我宁愿使用名称,因为我的模型是使用 sqlacodegen 生成的。

此外,SQLAlchemy 文档说我可以将名称 ( http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html#many-to-many ) 与 caveta 一起使用“使用声明性扩展”。我在谷歌上搜索了导致我 this 的术语.问题是在我的情况下如何扩充 Base。

# model.py
# coding: utf-8
from sqlalchemy import Column, Date, DateTime, ForeignKey, ForeignKeyConstraint, Index, Integer, Numeric, String, Table, Text, text
from sqlalchemy.orm import backref, relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
metadata = Base.metadata

t_Documented = Table(
    'Documented', metadata,
    Column('id', Integer, primary_key=True),
    Column('note_id', ForeignKey(u'MySchema.Note.id'), nullable=False),
    Column('document_id', ForeignKey(u'MySchema.Document.id'), nullable=False, index=True),
    Column('inserted', DateTime, nullable=False, server_default=text("'0000-00-00 00:00:00'")),
    Column('updated', DateTime, nullable=False, server_default=text("'0000-00-00 00:00:00'")),
    Index('Documented_AK1', 'note_id', 'document_id'),
    schema='MySchema'
)

class Note(Base):
    __tablename__ = 'Note'
    __table_args__ = {u'schema': 'MySchema'}

    id = Column(Integer, primary_key=True)

class Document(Note):
    __tablename__ = 'Document'
    __table_args__ = {u'schema': 'MySchema'}

    id = Column(ForeignKey(u'MySchema.Note.id'), primary_key=True)
    title = Column(String(100), nullable=False)
    author = Column(String(100), nullable=False)

    notes = relationship(u'Note', secondary='Documented', backref='documents')

使用 SQLAlchemy 0.9.4 和 Python 2.6.6。连接器是 MySQLDB,我使用的是 MySQL 数据库。

最佳答案

你的表有一个“MySchema”的模式,所以它必须是它的一部分:

notes = relationship(u'Note', secondary='MySchema.Documented', backref='documents')

关于python - 只能使用关联表对象定义二级关系,不能使用名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23176794/

相关文章:

python - 元组索引 numpy 数组的奇怪行为

python - SqlAlchemy 超前缓存?

python - sqlalchemy:为什么在将它分配给 Session 对象之前创建一个 sessionmaker?

python - 如何在 marshmallow-sqlalchemy 中使用嵌套对象加载

Python 系统日志和扩展字符

python - 如何在每隔一个元素处组合两个字符串列表?

python - 如何列出具有 3 种不同状态的 3x3 板的所有可能性?

python - SQLAlchemy - 获取表的创建日期

python - 设置python环境-安装后找不到模块

Python OAuth 错误 "Invalid Grant"