在 SQL 中,外键必须映射到一个特定的表,因此您需要将外键放在指向 'info.id' 的 'car' 或 'suv' 表中。
对于您需要的东西,这可能有点过头了,但这是解决它的一种方法(假设您实际上确实希望每辆汽车只有一个信息):
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy import event
Base = declarative_base()
class Info(Base):
__tablename__ = 'info'
id = Column(Integer(), primary_key=True)
type = Column(String())
# NOTE: can't use backref='info' because we need the attributes defined
# directly on both classes so we can attach event listeners
car = relationship('Car', back_populates='info', uselist=False)
suv = relationship('Suv', back_populates='info', uselist=False)
@property
def item(self):
# could check self.type here if you wanted
return self.car or self.suv
@item.setter
def item(self, value):
if isinstance(value, Car):
self.car = value
elif isinstance(value, Suv):
self.suv = value
elif value is None:
self.car = None
self.suv = None
else:
raise ValueError("item must be Car or Suv")
@event.listens_for(Info.car, 'set')
def _car_set_event(target, value, oldvalue, initiator):
if value is not None:
target.type = 'car'
if target.suv:
target.suv = None
elif target.type == 'car':
target.type = None
@event.listens_for(Info.suv, 'set')
def _suv_set_event(target, value, oldvalue, initiator):
if value is not None:
target.type = 'suv'
if target.car:
target.car = None
elif target.type == 'suv':
target.type = None
class Car(Base):
__tablename__ = 'car'
id = Column(Integer(), primary_key=True)
info_id = Column(Integer(), ForeignKey('info.id'))
info = relationship(Info, back_populates='car')
@event.listens_for(Car.info, 'set')
def _car_info_set_event(target, value, oldvalue, initiator):
if value is not None:
value.type = 'car'
class Suv(Base):
__tablename__ = 'suv'
id = Column(Integer(), primary_key=True)
info_id = Column(Integer(), ForeignKey('info.id'))
info = relationship(Info, back_populates='suv')
@event.listens_for(Suv.info, 'set')
def _suv_info_set_event(target, value, oldvalue, initiator):
if value is not None:
value.type = 'suv'
事件侦听器的复杂性使您在执行以下操作时自动管理类型:
car1.info = Info()
assert (car1.info.type == 'car')
或者
info1 = car1.info
info1.suv = suv1
assert (car1.info is None)
assert (info1.type == 'suv')
如果你想自己保持 Info.type、Info.car 和 Info.suv 一致,你可以省略所有的事件监听函数。
为 CarInfo 和 SuvInfo 提供单独的对象和表也是一个非常合理的选择,并且完全避免了所有这些复杂性。