是否可以构建一个SQLAlchemy关系,该关系将接受从同一Base
继承的任何实例?理想情况下,它为实例的ID维护一个外键,为实例的类型维护第二个外键。
例如,此Variable
类在其自身与applies_to
类之间存在关系Car
。
# some overhead, for completeness
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, Session
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:')
session = Session(bind=engine)
Base = declarative_base()
# defining my classes
class Variable(Base):
__tablename__ = 'variables'
id = Column(Integer, primary_key=True)
name = Column(String)
value = Column(Integer)
applies_to_id = Column(Integer, ForeignKey('cars.id'))
applies_to = relationship('Car')
class Car(Base):
__tablename__ = 'cars'
id = Column(Integer, primary_key=True)
class Truck(Base):
__tablename__ = 'trucks'
id = Column(Integer, primary_key=True)
Base.metadata.create_all(engine)
有了它,我可以为该车制作Car
和Variable
并提交到数据库。
car = Car()
var1 = Variable(name="speed", value=50, applies_to=car)
session.add(car)
session.add(var1)
session.commit()
但我不能对Truck
和Variable
做类似的事情。
truck = Truck()
var2 = Variable(name="speed", value=50, applies_to=truck)
session.add(truck)
session.add(var2)
session.commit()
AssertionError: Attribute 'applies_to' on class '<class '__main__.Variable'>' doesn't handle objects of type '<class '__main__.Truck'>'
我想修改Variable
类以支持Truck
以及通过Base
关系从applies_to
继承的任何其他类。
编辑:与sqlalchemy generic foreign key (like in django ORM)类似,但该解决方案要求所有类都从HasAddresses
mixin继承并在这些类上通过addresses
处理backref。是否存在仅编辑Variable
类并且不对其他类维护backref的解决方案?