您将不得不从使用简单的多对多关系切换为使用“关联对象”,这基本上只是获取关联表并为其提供适当的类映射。然后,您将与
User和定义一对多关系
Community:
class Membership(db.Model): __tablename__ = 'community_members' id = db.Column('id', db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) community_id = db.Column(db.Integer, db.ForeignKey('community.id')) time_create = db.Column(db.DateTime, nullable=False, default=func.now()) community = db.relationship(Community, backref="memberships") user = db.relationship(User, backref="memberships")class Community(db.Model): __tablename__ = 'community' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False, unique=True)但是您可能只是偶尔对创建时间感兴趣。您想恢复旧的关系!好吧,您不想设置
relationship两次;因为sqlalchemy会以某种方式认为您想要
两个
关联;这一定意味着不同!您可以通过添加关联代理来实现。
from sqlalchemy.ext.associationproxy import association_proxyCommunity.members = association_proxy("memberships", "user")User.communities = association_proxy("memberships", "community")


