1

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

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: 'Friends' 对象没有属性 'foreign_keys”

怎么了?

4

1 回答 1

1

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

于 2012-11-24T13:27:18.250 回答