【问题标题】:SQLAlchemy one-to-many relationships with many possible different modelsSQLAlchemy 与许多可能的不同模型的一对多关系
【发布时间】:2017-03-20 01:16:06
【问题描述】:

基本上,我要做的是实施一个系统,让网站上的帖子可以用表情符号做出反应。也可以对这些帖子的评论做出反应。为了保持干净,我想为所有对帖子和 cmets 的反应制作一个表格,因为它们基本上是相同的。所以基本上我有两个一对多的关系,反应表总是“多”,两个可能的模型/表充当“一个”。这基本上是我想用 Flask-SQLAlchemy 做的事情:

class Reaction(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    code = db.Column(db.String(32), nullable=False) # The emoji code in format ":thumbsup:"
    user_id = db.Column(db.Integer, db.ForeignKey("user.id")) # The user reacting
    post_id = db.Column(db.Integer, db.ForeignKey("post.id"), nullable=True)
    comment_id = db.Column(db.Integer, db.ForeignKey("comment.id"), nullable=True)

class Post(db.Model):
    ....
    reactions = db.relationship("Reaction", lazy="dynamic", cascade="all, delete-orphan")

class Comment(db.Model):
    ....
    reactions = db.relationship("Reaction", lazy="dynamic", cascade="all, delete-orphan")

如果我是正确的,这应该有效,对吧?但是有没有更好、更标准的方法来做这样的事情?

【问题讨论】:

    标签: python python-3.x flask sqlalchemy flask-sqlalchemy


    【解决方案1】:

    您可以为此使用Single Table Inheritance(维基百科)。 SQLAlchemy 通过功能 Mapping Class Inheritance Hierarchies(SQLAlchemy 文档)支持这一点。

    对于单表继承,您在表上创建一个字段来区分帖子和评论,并创建多个模型类并将特定参数传递给Mapper(通过__mapper_args__ 属性),以便 SQLAlchemy 使用此“鉴别器” column" 以了解每行代表哪种类型的对象。

    示例:

    class Post(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        # columns omitted
        post_type = db.Column(db.Integer)
    
        __table_name__ = 'post_or_comment'
        __mapper_args__ = {
            'polymorphic_on': post_type,
            'polymorphic_identity': 1,
        }
    
    class Comment(Post):
        __mapper_args__ = {
            'polymorphic_identity': 2,
        }
    

    【讨论】:

      猜你喜欢
      • 2016-08-23
      • 2012-07-28
      • 1970-01-01
      • 2021-03-01
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多