Including two related objects in SQLAlchemy

I get a (possibly trivial) error, but I don’t know at all about the possible reasons. I want to insert two objects into a database using SQLAlchemy. These objects are connected, here are the declarations. Class User:

class User(Base):
    __tablename__ = 'cp_user'

    id = Column(Integer, Sequence('id_seq'), primary_key=True)
# ... more properties

Class image (a user can have many of them):

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

I try to insert a new image after I retrieved the desired user from the database or simply created it:

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()

This happens with an error: AttributeError: 'RowTuple' object has no attribute '_sa_instance_state'

I tried to move the author's assignment to the constructor - the same error. I cannot assign identifiers directly - this violates the idea of ​​ORM.

What am I doing wrong?

+3
source share
1 answer

, not(user) .

User.name, , .

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

, . . , , , . . .

. , . , (, ..).

+5

Source: https://habr.com/ru/post/1720128/


All Articles