有一个info
表,它与car
表或suv
表有关系。
在info.type
字段中指定了它。
那么如何根据记录的类型数据在飞行中创建关联?
class Info(Base):
item_id = Column(ForeignKey('cars-or-suvs-table.id'))
type = Column(String())
class Car(Base):
- data -
info = relationship('Info', backref="car")
class Suv(Base):
- data -
info = relationship('Info', backref="suv")
编辑:我已经在表中填充了数据,因此我无法更改数据库架构。
答案 0 :(得分:2)
由于您正在寻找一种不需要将外键移动到其他表的解决方案,您可以尝试这种方法:
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import sql
Base = declarative_base()
engine = sqlalchemy.create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=engine)
session = Session()
class Info(Base):
__tablename__ = 'info'
id = Column(Integer(), primary_key=True)
type = Column(String())
item_id = Column(Integer())
@property
def item(self):
if self.type == 'car':
return self._car
elif self.type == 'suv':
return self._suv
return None
@item.setter
def item(self, value):
if value is not None:
self.item_id = value.id
self.type = value.__tablename__
else:
self.item_id = None
class Car(Base):
__tablename__ = 'car'
id = Column(Integer(), primary_key=True)
info = relationship(Info, primaryjoin=sql.and_(id == Info.item_id, Info.type == 'car'), foreign_keys=Info.item_id, uselist=False, backref='_car')
class Suv(Base):
__tablename__ = 'suv'
id = Column(Integer(), primary_key=True)
info = relationship(Info, primaryjoin=sql.and_(id == Info.item_id, Info.type == 'suv'), foreign_keys=Info.item_id, uselist=False, backref='_suv')
我将Info.car重命名为Info._car,因为即使.type是'suv',._car也不可避免地会成为虚假的汽车对象。
我已经离开了事件监听器的东西以保持简单,但你绝对可以从我的其他答案调整你需要的东西,以避免事情进入不一致的状态。
答案 1 :(得分:1)
在SQL中,外键必须映射到一个特定的表,因此您需要将外键放在'car'或'suv'表中,指向'info.id'。
这对你所需要的东西来说可能有点过头了,但这是解决问题的一种方法(假设你确实希望每辆车只有一个信息):
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提供单独的对象和表也是一个非常合理的选择,并且完全避免所有这些复杂性。