SQLAlchemy与任何类的关系

时间:2018-06-07 02:10:56

标签: python sqlalchemy

是否可以构建一个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)

有了它,我可以为该车制作CarVariable并提交到数据库。

car = Car()
var1 = Variable(name="speed", value=50, applies_to=car)
session.add(car)
session.add(var1)
session.commit()

但我不能对TruckVariable做类似的事情。

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的解决方案?

0 个答案:

没有答案