SqlAlchemy没有定义这样的多态身份

时间:2014-06-08 14:42:21

标签: python orm sqlalchemy

我正在尝试存储第三方网站的用户oauth详细信息,BaseConnection表用于存储连接的基本信息

class BaseConnection(Base):
    __tablename__ = "BaseConnection"
    id = Column(Integer, primary_key=True)
    username = Column(Unicode(255),
                      ForeignKey('users.username'))
    type = Column(Unicode(255))
    is_active = Column(Boolean, default=False)
    last_connection = Column(DateTime, onupdate=datetime.utcnow)

    __mapper_args__ = {
        'polymorphic_identity': 'BaseConnection',
        'polymorphic_on': type
    }

    def __init__(self, username, type, is_active):
        self.username = username
        self.type = type
        self.is_active = is_active

Twitter连接用于存储Twitter帐户的详细信息

class TwitterConnection(Base):
    __tablename__ = "TwitterConnection"

    connection_id = Column(Integer, ForeignKey('BaseConnection.id'),
                           primary_key=True)
    uid = Column(Unicode(255))
    access_key = Column(Unicode(255))
    access_secret = Column(Unicode(255))
    twitter_username = Column(Unicode(255))
    refresh_date = Column(DateTime)

    __mapper_args__ = {
        'polymorphic_identity': 'TwitterConnection'
    }

    def __init__(self, connection_id, 
                 uid, access_key, access_secret, twitter_username):
        self.connection_id = connection_id
        self.uid = uid
        self.access_key = access_key
        self.access_secret = access_secret
        self.twitter_username = twitter_username
        self.refresh_date = datetime.now()

然后我使用代码

将第一个细节添加到表中
base_connection = BaseConnection('admin', TwitterConnection.__name__, True)
base_connection.last_connection = datetime.now()
DBSession.add(base_connection)
DBSession.flush()
tconnection = TwitterConnection(
                 base_connection.id,
                 uid=u'1234',
                 access_key=u'dummy',
                 access_secret=u'dummy',
                 twitter_username='dummy')
DBSession.add(tconnection)
DBSession.flush()
transaction.commit()

我尝试编写查询以查找具有特定用户名的用户的所有第三方帐户

qry = BaseConnection.query.filter(
                BaseConnection.username==username)
qry.all()

以上查询给出了错误

`AssertionError: No such polymorphic_identity u'TwitterConnection' is defined

我是sqlalchemy的新手,感谢您的帮助。谢谢。

1 个答案:

答案 0 :(得分:2)

对不起,

class TwitterConnection(Base):

应该是

class TwitterConnection(BaseConnection):