I thought about it myself.
What I needed to do:
MyUser.friends.append(Friend(MyUser.id, MyFriend.id))
and then commit the update.
Update:
Well, I found the right way to do what I wanted. At first I don't need a Friend table / class. Full code:
association_table = db.Table('association', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('friend_id', db.Integer, db.ForeignKey('user.id')) ) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True) password = db.Column(db.String(30)) email = db.Column(db.String(45), unique=True) friends = db.relationship("User", secondary=association_table, backref='added_by', primaryjoin=id == association_table.c.user_id, secondaryjoin=id == association_table.c.friend_id)
With this, I can now do the following:
>>> user1 = User.query.filter_by(id=1).first() >>> user1.friends [] >>> user2 = User.query.filter_by(id=2).first() >>> user1.friends.append(user2) >>> user1.friends [<User('user1',' user1@admin.com ','2')>] >>> user1.friends[0].added_by [<User('admin',' admin@admin.com ','1')>]
source share