Flask/Sqlaclemy: How to do one to many polymorphic inheritance

这一生的挚爱 提交于 2019-12-24 20:13:25

问题


I am attempting to create a one to many polymorphic relationship in flask/sqlalchemy. The concept is to provide temporary to certain data using an authorizations table. The table will have two fields, authorizable_id and authorizable_type. The authorizable_id refers to the id of the entry it is referring to. It is not a foreign key as it can refer to different tables. The authorizable_type determines which table it is referring to. For example, for a file, it is 'FILE'.

I've seen how to do something similar but the sqlalchemy documenation is pretty implicit about the role of fields. In addition, they require that the table being referred to (here File), have an id that is a foreign key that refers to the table that holds the relationship (discriminator/id). I am doing the opposite, where the polymorphic relationship holds the id of the asset. I was hoping the sqlalchemy had a value such as "polymorphic_field" where you can indicate which field name. I've added the code below. Any guidance is very appreciated. Thank you!

class AuthorizableInterface(Model):
    __mapper_args__ = {
        'polymorphic_identity':'AUTHORIZABLE',
    }

class Authorization(Model):
    __tablename__ = 'authorizations'
    token = Column(String(254), nullable=False)
    ...
    authorizable_id = Column(Integer(), ForeignKey(AuthorizableInterface.id))
    authorizable_type = Column(String(254), nullable=False)
    __mapper_args__ = {
        'polymorphic_on': authorizable_type,
        'polymorphic_field' 'authorizable_id' // not a real thing, what i want to do
    }


class File(AuthorizableInterface):
    __tablename__ = 'files'
    url = Column(Text(1024), nullable=False)
    provider_id = Column(Integer(), ForeignKey('file_providers.id'))
    __mapper_args__ = {
        'polymorphic_identity':'FILE'
    }

class AnotherAuthorizableThing(AuthorizableInterface): 
    ...
    __mapper_args__ = {
        'polymorphic_identity':'THING'
    }

来源:https://stackoverflow.com/questions/45681053/flask-sqlaclemy-how-to-do-one-to-many-polymorphic-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!