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

时间:2011-09-14 14:21:03

标签: orm many-to-many sqlalchemy flask-sqlalchemy

我有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?

2 个答案:

答案 0 :(得分:54)

您必须从使用普通的多对多关系切换到使用“关联对象”,这基本上只是采用关联表并为其提供正确的类映射。然后,您将定义与UserCommunity的一对多关系:

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会认为你想要两个关联;这必须意味着不同的东西!您可以通过添加association proxy.

来完成此操作
from sqlalchemy.ext.associationproxy import association_proxy

Community.members = association_proxy("memberships", "user")
User.communities = association_proxy("memberships", "community")

答案 1 :(得分:0)

如果您只需要已知user_id的查询community_memberscommunity表(例如user_id = 2),则在SQLAlchemy中,您可以执行:

session.query(community_members.c.time_create, Community.name).filter(community_members.c.user_id==2)

获得结果。