Python SQLAlchemy外键可以属于几种可能的模型之一?
我有一个模型Python SQLAlchemy外键可以属于几种可能的模型之一?,python,mysql,python-3.x,sqlalchemy,polymorphic-associations,Python,Mysql,Python 3.x,Sqlalchemy,Polymorphic Associations,我有一个模型Animals,其中字段locationID是一个外键,可以是Forests.id或Zoos.id。假设Forests.id和Zoos.id从不相同 问题:这是SqlAlchemy可以做到的吗 Base = declarative_base() class Forests(Base): __tablename__ = 'forests' id = Column(String(16), primary_key=True)
Animals
,其中字段locationID
是一个外键,可以是Forests.id
或Zoos.id
。假设Forests.id
和Zoos.id
从不相同
问题:这是SqlAlchemy可以做到的吗
Base = declarative_base()
class Forests(Base):
__tablename__ = 'forests'
id = Column(String(16), primary_key=True)
class Zoos(Base):
__tablename__ = 'zoos'
id = Column(String(16), primary_key=True)
class Animals(Base):
__tablename__ = 'animals'
name = Column(String(16), primary_key=True)
locationID = Column(String(16), ForeignKey(Forests.id or Zoos.id)) # something like this...
更多详细信息 在Sqlalchemy文档中的一个示例中发现了类似的内容,例如
class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
name = Column(String(50))
type = Column(String(50))
__mapper_args__ = {
'polymorphic_identity':'employee',
'polymorphic_on':type
}
class Engineer(Employee):
__tablename__ = 'engineer'
id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
engineer_name = Column(String(30))
__mapper_args__ = {
'polymorphic_identity':'engineer',
}
class Manager(Employee):
__tablename__ = 'manager'
id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
manager_name = Column(String(30))
__mapper_args__ = {
'polymorphic_identity':'manager',
}
Engineer
和Manager
在employee
表中都有外键
但是,我需要的是Employee
在engineer
或manager
表中具有外键,类似于下面的代码
下面的代码只是为了说明,显然不起作用
在这种情况下,我们可能需要进一步研究我们的模型,一个好的问题是: 动物园和森林有什么共同点吗
- 动物住在那里
- GPS坐标
- 人类用来指代他们的名字
- 动物园通常收取入场费
- 动物园有围栏
- 森林对我们的动物居民来说有着重要的意义
动物的住所
基于文档中的示例,我们可以这样定义:
class Dwelling(Base):
__tablename__ = 'dwelling'
id = Column(Integer, primary_key=True)
name = Column(String(50))
type = Column(String(50))
__mapper_args__ = {
'polymorphic_identity':'dwelling',
'polymorphic_on':type
}
class Forest(Dwelling):
__tablename__ = 'forest'
id = Column(Integer, ForeignKey('dwelling.id'), primary_key=True)
biome = Column(String(30))
__mapper_args__ = {
'polymorphic_identity':'forest',
}
class Zoo(Dwelling):
__tablename__ = 'zoo'
id = Column(Integer, ForeignKey('dwelling.id'), primary_key=True)
fee = Column(Integer)
__mapper_args__ = {
'polymorphic_identity':'zoo',
}
对于我们的动物
,这将如下所示:
class Animal(Base):
__tablename__ = 'animal'
name = Column(String(16), primary_key=True)
location = Column(Integer, ForeignKey(Dwelling.id))
希望这能有所帮助。我也很好奇什么是森林。生物群落
?似乎当我插入森林
或动物园
时,住宅
表会自动填充。。。这是怎么发生的?
class Animal(Base):
__tablename__ = 'animal'
name = Column(String(16), primary_key=True)
location = Column(Integer, ForeignKey(Dwelling.id))