一尘不染

SQLAlchemy ManyToMany带有附加字段的辅助表

python

我有3个表:User,Community,community_members(用于用户和社区的many2many关系)。

我使用Flask-SQLAlchemy创建此表:

community_members = db.Table('community_members',
                db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
                db.Column('community_id', db.Integer, db.ForeignKey('community.id')),
                )


class Community(db.Model):
    __tablename__ = 'community'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False, unique=True)
    members = db.relationship(User, secondary=community_members,
                            backref=db.backref('community_members', lazy='dynamic'))

现在,我想像这样向community_members添加其他字段:

community_members = db.Table('community_members',
                db.Column('id', db.Integer, primary_key=True),
                db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
                db.Column('community_id', db.Integer, db.ForeignKey('community.id')),
                db.Column('time_create', db.DateTime, nullable=False, default=func.now()),
                )

现在在python shell中,我可以这样做:

创建社区:

> c = Community()
> c.name = 'c1'
> db.session.add(c)
> db.session.commit()

将成员添加到社区:

> u1 = User.query.get(1)
> u2 = User.query.get(2)
> c.members.append(u1)
> c.members.append(u2)
> db.session.commit()

> c.members
[<User 1>, <User 2>]

好的,这可行。

但是,现在我如何获得community_members表的time_create?


阅读 134

收藏
2020-12-20

共1个答案

一尘不染

您将不得不从使用简单的多对多关系切换为使用“关联对象”,这基本上只是获取关联表并为其提供适当的类映射。然后,您将与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_proxy

Community.members = association_proxy("memberships", "user")
User.communities = association_proxy("memberships", "community")
2020-12-20