我正在编写一个框架来帮助人们高效地处理数据库中的不同数据模型(意味着批量操作)。我想为多对多关系创建一个基类,可以这样使用:
from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class CustomBase(Base):
__abstract__ = True
metadata = MetaData()
class CustomManyToManyBase(CustomBase):
__abstract__ = True
class Parent(CustomBase):
__tablename__ = 'parents'
id = Column(Integer, primary_key=True)
class Child(CustomBase):
__tablename__ = 'children'
id = Column(Integer, primary_key=True)
class Family(CustomManyToManyBase):
models = (Parent, Child)
然后它将自动获取模型的主键,并为关联表创建必要的列,与此等效(就像我编写了以下内容):
class Family(CustomBase):
parent_id = ForeignKey('parent.id')
child_id = ForeignKey('child.id')
在我的理解中,我不能使用relationship()
,因为它在批量操作中被省略,但是我可以很容易地从数据中提取密钥对,并使用bulk_insert_mappings
。我需要用于其他通用数据操作任务的模型类,因此我认为可能有一种方法可以使用这些信息来创建必要的列。你知道吗
如果我想在关联表中存储其他信息呢?你知道吗
这样做的目的是为基类提供预先编写的批量操作,因此SQLAlchemy的新手用户也可以高效地工作(他们甚至可能不知道SQLAlchemy)。你知道吗
我能够创建这样的类,但不是作为基类,而是作为一个mixin:
可用作:
您可以找到详细信息here。你知道吗
相关问题 更多 >
编程相关推荐