SQLAlchemy - Self referential Many-to-many relationship with extra column
All you need is to add primaryjoin in your table and also making two foreignkey in table of Friendship, 'primary_key' too. you also need to make friendship as a class.
class Friendship(db.Model): __tablename__ = 'friend' fk_user_from = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True) fk_user_to = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True) extra_field = db.Column(db.Integer)class User (db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) user_to = db.relationship('Friendship',backref='to', primaryjoin=id==Friendship.fk_user_to) user_from = db.relationship('Friendship',backref='from', primaryjoin=id==Friendship.fk_user_from )
And to add a friend you need to define Friendship like:
friend = Friendship(extra_field=0 , to=me , from=my_friend)
I have answered to a similar question that solves Self-referential many-to-many relationship with Association Object.
See https://stackoverflow.com/a/62281276/9387542
Also, if you solely looking for establing a frienship model, I suggest you to establish Many-to-many relationship with the model from https://stackoverflow.com/a/7317251/9387542