【问题标题】:SQLAlchemy ManyToMany secondary table with additional fields带有附加字段的 SQLAlchemy ManyToMany 辅助表
【发布时间】:2011-09-14 14:21:02
【问题描述】:

我有 3 个表:用户、社区、社区成员(用于许多用户和社区的关系)。

我使用 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 呢?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 我使用了您的解决方案并且它有效,但我仍然遇到问题。 Community.members(与关联代理一起添加)是否有可能返回一个 AppenderBaseQuery,我可以添加更多过滤器,例如Community.members.filter_by(...)?我习惯于在关系声明中使用lazy=dynamic 来处理简单的多对多关系,但是在将类映射到关联表之后,我似乎不能再这样做了。
    • 你有没有发现@stefanobaldo 的解决方案 - 如果你发现了,那将非常有帮助!
    【解决方案2】:

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

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

    得到结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 2021-12-05
      相关资源
      最近更新 更多