如何在SqlAlchemy中自动创建多对多映射表?

2024-09-28 21:01:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个框架来帮助人们高效地处理数据库中的不同数据模型(意味着批量操作)。我想为多对多关系创建一个基类,可以这样使用:

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)。你知道吗


Tags: fromimportabstractidtruebasesqlalchemy批量
1条回答
网友
1楼 · 发布于 2024-09-28 21:01:18

我能够创建这样的类,但不是作为基类,而是作为一个mixin:

from sqlalchemy.inspection import inspect
from sqlalchemy import Column, ForeignKey, Integer, Table

class ManyToManyMixin:
    @classmethod
    def __table_cls__(cls, *args, **kwargs):
        return Table(
            *args,
            *[Column(
                '{}_{}'.format(model.__name__.lower(), col.name),
                col.type,
                ForeignKey(col),
                primary_key=True
              ) for model in cls.models for col in inspect(model).primary_key]
            **kwargs
        )

可用作:

class Family(ManyToManyMixin, CustomBase):
    __tablename__ = 'families'
    other_value = Column(Integer) # just to show that it does not cause any restrictions

    models = (Parent, Child)

您可以找到详细信息here。你知道吗

相关问题 更多 >