SQLAlchemy中是否可以使用多级多态?

时间:2010-05-18 16:53:56

标签: python sqlalchemy

SQLAlchemy中是否可以有多级多态?这是一个例子:

class Entity(Base):
    __tablename__ = 'entities'
    id = Column(Integer, primary_key=True)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    entity_type = Column(Unicode(20), nullable=False)
    __mapper_args__ = {'polymorphic_on': entity_type}

class File(Entity):
    __tablename__ = 'files'
    id = Column(None, ForeignKey('entities.id'), primary_key=True)
    filepath = Column(Unicode(255), nullable=False)
    file_type = Column(Unicode(20), nullable=False)
    __mapper_args__ = {'polymorphic_identity': u'file', 'polymorphic_on': file_type)

class Image(File):
    __mapper_args__ = {'polymorphic_identity': u'image'}
    __tablename__ = 'images'
    id = Column(None, ForeignKey('files.id'), primary_key=True)
    width = Column(Integer)
    height = Column(Integer)

当我调用Base.metadata.create_all()时,SQLAlchemy会引发以下错误:

IntegrityError: (IntegrityError) entities.entity_type may not be NULL`.

如果我删除Image模型和polymorphic_on中的File密钥,则此错误消失。

是什么给出了?

2 个答案:

答案 0 :(得分:13)

Yes。您的代码的问题在于,当您必须瞄准树的头部时,将Image设为一种文件,使Image成为一种实体。

示例:

from sqlalchemy import (Table, Column, Integer, String, create_engine,
    MetaData, ForeignKey)
from sqlalchemy.orm import mapper, create_session
from sqlalchemy.ext.declarative import declarative_base

e = create_engine('sqlite:////tmp/foo.db', echo=True)
Base = declarative_base(bind=e)

class Employee(Base):
    __tablename__ = 'employees'

    employee_id = Column(Integer, primary_key=True)
    name = Column(String(50))
    type = Column(String(30), nullable=False)

    __mapper_args__ = {'polymorphic_on': type}

    def __init__(self, name):
        self.name = name

class Manager(Employee):
    __tablename__ = 'managers'
    __mapper_args__ = {'polymorphic_identity': 'manager'}

    employee_id = Column(Integer, ForeignKey('employees.employee_id'),
        primary_key=True)
    manager_data = Column(String(50))

    def __init__(self, name, manager_data):
        super(Manager, self).__init__(name)
        self.manager_data = manager_data

class Owner(Manager):
    __tablename__ = 'owners'
    __mapper_args__ = {'polymorphic_identity': 'owner'}

    employee_id = Column(Integer, ForeignKey('managers.employee_id'),
        primary_key=True)
    owner_secret = Column(String(50))

    def __init__(self, name, manager_data, owner_secret):
        super(Owner, self).__init__(name, manager_data)
        self.owner_secret = owner_secret

Base.metadata.drop_all()
Base.metadata.create_all()

s = create_session(bind=e, autoflush=True, autocommit=False)    
o = Owner('nosklo', 'mgr001', 'ownerpwd')
s.add(o)
s.commit()

答案 1 :(得分:2)

不可能(见SQL ALchemy doc):

  

目前,通常只能在层次结构中最基类的类上设置一个鉴别器列。 “Cascading”多态列尚不支持。

因此,您应该遵循@nosklo提案来改变您的遗产模式。