SqlSoup related()用于多对多关系抛出异常

时间:2010-11-30 23:01:14

标签: many-to-many sqlalchemy sqlsoup

我正在使用以下代码将SqlSoup与现有数据库一起使用。

import sqlalchemy
from sqlalchemy.ext.sqlsoup import SqlSoup
from sqlalchemy.orm import backref

engine = sqlalchemy.create_engine('postgresql:///test')
db = SqlSoup(engine)
db.books.relate('author', db.authors)
db.books.relate('tags', db.tags, secondary=db.tags2books, backref=backref('books', lazy=False))

但是,最后一次relate()调用会引发异常:

Traceback (most recent call last):
  File "sqlsoup-test.py", line 10, in <module>
    db.books.relate('tags', db.tags, secondary=db.tags2books, backref=backref('books', lazy=False))
  File "/usr/lib64/python2.6/site-packages/sqlalchemy/ext/sqlsoup.py", line 384, in relate
    class_mapper(cls)._configure_property(propname, relationship(*args, **kwargs))
  File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/mapper.py", line 758, in _configure_property
    prop.init()
  File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/interfaces.py", line 476, in init
    self.do_init()
  File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/properties.py", line 895, in do_init
    self._determine_joins()
  File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/properties.py", line 1010, in _determine_joins
    self.secondary)
  File "/usr/lib64/python2.6/site-packages/sqlalchemy/orm/properties.py", line 1002, in _search_for_join
    return join_condition(mapper.local_table, table)
  File "/usr/lib64/python2.6/site-packages/sqlalchemy/sql/util.py", line 219, in join_condition
    for fk in b.foreign_keys:
AttributeError: 'MappedTags2books' object has no attribute 'foreign_keys'

使用以下定义创建表:

authors_table = Table('authors', metadata,
    Column('id', Integer, primary_key=True),
    Column('name', String, nullable=False, index=True)
)

books_table = Table('books', metadata,
    Column('id', Integer, primary_key=True),
    Column('author_id', Integer,
        ForeignKey('authors.id', onupdate='CASCADE', ondelete='CASCADE'),
        nullable=False),
    Column('title', String, nullable=False, index=True)
)

tags_table = Table('tags', metadata,
    Column('id', Integer, primary_key=True),
    Column('tag', String, index=True, unique=True, nullable=False)
)

tags2books_table = Table('tags2books', metadata,
    Column('tag_id', Integer,
        ForeignKey('tags.id', onupdate='CASCADE', ondelete='CASCADE'),
        primary_key=True),
    Column('book_id', Integer,
        ForeignKey('books.id', onupdate='CASCADE', ondelete='CASCADE'),
        primary_key=True)
)

如果你打算问“为什么他在使用真正的SQLAlchemy时会使用SqlSoup?”:我正在写一篇关于SQLAlchemy的学期论文,我在一章中提到了SqlSoup,我想添加一个例子。而且比使用我用于SA示例的数据库更容易......

1 个答案:

答案 0 :(得分:1)

看起来secondary不能是映射类。传递表可以修复错误:

db.books.relate('tags', db.tags, secondary=db.tags2books._table, backref=backref('books', lazy=False))