AttributeError:'unicode'对象没有属性'_sa_instance_state'

时间:2011-09-03 22:40:22

标签: python sqlalchemy

我正在学习如何使用SQLAlchemy。我正在尝试执行以下操作,但将标题和链接存储在两个单独的表中:

temp = Submissions(title=u'Facebook Homepage', link=u'http://facebook.com')
session.add(temp)
session.flush()
transaction.commit()

通过:

class Links(Base):
    __tablename__ = 'links'
    id = Column(Integer, primary_key=True)
    link = Column(Text)
    created = Column(TIMESTAMP(), default=datetime.now())

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

class Submissions(Base):
    __tablename__ = 'submissions'
    id = Column(Integer, primary_key=True)
    created = Column(TIMESTAMP(), default=datetime.now())
    title = Column(Text)
    link_id = Column(Integer, ForeignKey('links.id'))
    link = relation(Links)

    def __init__(self, title, link):  
        self.title = title
        self.link = link

但是,我总是得到这个错误:

AttributeError: 'unicode' object has no attribute '_sa_instance_state'

发生了什么事?有没有更好的方法来编码呢?

2 个答案:

答案 0 :(得分:8)

relationship你无法做到这一点。

您需要安排以某种方式查找Link

最明显的是直接查找。

submission_link = session.query(Links) \
                         .filter(Links.link == u'http://facebook.com') \
                         .first()
if submission_link is None:
    submission_link = Links(link=u'http://facebook.com')
    session.add(submission_link)

submission = Submissions(title=u'Facebook Homepage', link=submission_link)
session.add(submission)
session.commit()

你也可以使用hybrid attributes来获得看起来更像你的例子的东西,但它更复杂。

此外,它已被relationshiprelation弃用。

答案 1 :(得分:2)

我将关系配置为one-to-oneuselist=False)并添加一个包含link关系的属性。 SA配置将如下所示,您的代码应该可以很好地创建,更新和删除链接。您可能需要在delete-orphan中配置cascade选项的关系。

...
class Submissions(Base):
    __tablename__ = 'submissions'
    id = Column(Integer, primary_key=True)
    created = Column(DateTime(), default=datetime.now())
    title = Column(Text)
    link_id = Column(Integer, ForeignKey('links.id'))
    link_rel = relation(Links, backref=backref("_submission", uselist=False))

    def __init__(self, title, link=None):
        self.title = title
        self.link = link

    @property
    def link(self):
        return self.link_rel and self.link_rel.link

    @link.setter
    def link(self, value):
        if value is None:
            self.link_rel = None
        elif self.link_rel is None:
            self.link_rel = Links(value)
        else:
            self.link_rel.link = value
...