Python; Sqlalchemy; join same table twice in Update

Viewed 29

I know that I'm not allowed to join Sqlalchemy in an update. I also know that I have to use the where or filter clause to do this. I tried to solve it via aliased(). However without real success. It will probably be due to the ForeignKeys and the relationship(). Maybe someone can help me here.

class Connection(base):
    __tablename__ = 'connection'
    fromUserID = Column(String(180),ForeignKey("user.userID"), primary_key=True, index=True)
    toUserID = Column(String(180), primary_key=True, index=True)
    friends = Column(Boolean)
    timeUpdated = Column(DateTime(timezone=True), onupdate=func.now())

This is my Table and i want to do this SQL:

def setAllFriends():
    sql =   "update connection as t1, connection as t2 \
            set t1.friends= True, t1.timeUpdated = '"+ datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') +"' \
            WHERE t1.fromUserID = t2.toUserID AND t1.toUserID=t2.fromUserID AND (t1.friends is Null or t1.friends is False)"
    db.execute(sql)
    db.commit()

yeah, my way works too but i would like to have something else.

    t1 = aliased(Connection)
    t2 = aliased(Connection)
    db.query(t1,t2).filter(t1.fromUserID == t2.toUserID).filter(t1.toUserID == t2.fromUserID).update({
        t1.friends : True,
        t2.timeUpdated : datetime.datetime.now()
    })

This end up with this error: sqlalchemy.exc.ArgumentError: SQL expression for WHERE/HAVING role expected, got <sqlalchemy.sql.annotation.AnnotatedAlias at 0x7fcf4560d190; anon_1>.

If you have a solution for my problem, I would also be very grateful for an explanation and not just for the error in the code. <3 thx.

0 Answers
Related