GabiMe
GabiMe

Reputation: 18483

SQLAlchemy: How to do many-to-many of table to itself (declarative way)

I am trying to define Many to Many relations of users. I followed the docs and the best I got was:

import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class Friends(Base):
    __tablename__ = 'friends'
    user1_id = sa.Column(sa.ForeignKey('users.id'), primary_key=True)
    user2_id = sa.Column(sa.ForeignKey('users.id'), primary_key=True)


class User(Base):
    __tablename__ = 'users'
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String(50))
    # many to many
    friends = orm.relationship('User', secondary=Friends, backref=Friends)

u = User(name='someuser')

But that would give me

"AttributeError: 'Friends' object has no attribute 'foreign_keys"

What's wrong?

Upvotes: 1

Views: 231

Answers (1)

Tobu
Tobu

Reputation: 25436

Here's your mistake: you set backref to the Friends class. Use a string.

Upvotes: 1

Related Questions