gpt4 book ai didi

python - SQLAlchemy 中是否可以实现多级多态性?

转载 作者:太空狗 更新时间:2023-10-29 20:13:14 27 4
gpt4 key购买 nike

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`.

如果我删除 File 中的 Image 模型和 polymorphic_on 键,这个错误就会消失。

什么给了?

最佳答案

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()

关于python - SQLAlchemy 中是否可以实现多级多态性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2859339/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com