SQLAlchemy:如何对表执行多对多(声明方式)

时间:2012-11-23 15:37:46

标签: sqlalchemy

我正在尝试定义多对多用户关系。我跟着文档,我得到的最好的是:

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

但那会给我

  

“AttributeError:'朋友'对象没有属性'foreign_keys'

怎么了?

1 个答案:

答案 0 :(得分:1)

这是你的错误:你将backref设置为Friends类。使用字符串。