问题
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