代码之家  ›  专栏  ›  技术社区  ›  Sergey Mikhanov

在SQLAlchemy中插入两个相关对象失败

  •  3
  • Sergey Mikhanov  · 技术社区  · 15 年前

    我得到了(可能是微不足道的)错误,但对可能的原因一无所知。我想使用sqlacalchemy在数据库中插入两个对象。这些对象是相关的,这里是声明。类用户:

    class User(Base):
        __tablename__ = 'cp_user'
    
        id = Column(Integer, Sequence('id_seq'), primary_key=True)
    # ... more properties
    

    类图片(用户可能有许多类图片):

    class Picture(Base):
        __tablename__ = 'picture'
    
        id = Column(Integer, Sequence('id_seq'), primary_key=True)
        authorId = Column('author_id', Integer, ForeignKey('cp_user.id'))
        author = relation(User, primaryjoin = authorId == User.id)
    # ... more properties
    

    我试图在从数据库中获取正确的用户后插入新图片,或者刚刚创建了新图片:

    s = newSession()
    user = s.query(User.name).filter("...some filter here...").first()
    if not(user):
        user = User()
        s.add(user)
        s.commit()
    
    picture = Picture()
    picture.author = user
    s.add(picture)
    s.commit()
    

    此操作失败,但有一个例外: AttributeError: 'RowTuple' object has no attribute '_sa_instance_state'

    我尝试将作者的赋值移到构造函数中——同样的错误。我不能直接分配ID——这打破了ORM的概念。

    我做错了什么?

    1 回复  |  直到 15 年前
        1
  •  5
  •   ebo    15 年前

    not(user)

    user = s.query(User).filter("...some filter here...").first()