使用简化的关联对象访问多对多关系中的额外列

时间:2013-04-24 07:23:01

标签: sqlalchemy

我正在尝试使用SQLAlchemy docs: Simplifying Association Objects

中的示例

我正在努力理解的是我如何访问special_key。最终,我希望能够做到这样的事情:

for user in users
    for keyword in user.keywords
        keyword.special_key

以下是示例中的代码:

class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String(64))

# association proxy of "user_keywords" collection
# to "keyword" attribute
keywords = association_proxy('user_keywords', 'keyword')

def __init__(self, name):
    self.name = name

class UserKeyword(Base):
__tablename__ = 'user_keyword'
user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
keyword_id = Column(Integer, ForeignKey('keyword.id'), primary_key=True)
special_key = Column(String(50))

# bidirectional attribute/collection of "user"/"user_keywords"
user = relationship(User,
            backref=backref("user_keywords",
                            cascade="all, delete-orphan")
        )

# reference to the "Keyword" object
keyword = relationship("Keyword")

def __init__(self, keyword=None, user=None, special_key=None):
    self.user = user
    self.keyword = keyword
    self.special_key = special_key

class Keyword(Base):
__tablename__ = 'keyword'
id = Column(Integer, primary_key=True)
keyword = Column('keyword', String(64))

def __init__(self, keyword):
    self.keyword = keyword

def __repr__(self):
    return 'Keyword(%s)' % repr(self.keyword)

我是否正确地遵循这种模式?

我的目标基本上是多对多的,额外的列包含一个布尔值。

1 个答案:

答案 0 :(得分:1)

这应该有效:

for user in users:
    for keyword in user.user_keywords:
        print keyword.special_key