对变量表使用SQLAlchemy映射

2024-05-03 09:24:06 发布

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

我有一个我们所有客户都使用的数据库。每个客户都有一组表,用他们的客户ID进行后期固定:

  • 分析\u 123
  • 嵌入\u 123
  • 下载\u 123

它是用“手动”SQL语句设置的,但是我正在努力将它移植到SQLAlchemy以便于维护。你知道吗

我更喜欢使用声明性语法,但是有没有什么方法可以动态设置模型的__tablename__值?如果我需要在一个线程环境中访问多个客户,会发生什么情况(我们很可能会使用不同的流程,但为了以防万一,我宁愿先介绍一下)。你知道吗

除了表名本身,所有关系(简单的单键外键)也必须在表之间正确映射。你知道吗


Tags: 方法模型id数据库声明sql客户环境
1条回答
网友
1楼 · 发布于 2024-05-03 09:24:06

一种方法是工厂化为客户所需的所有类。像下面这样的。。。(这只是个草图!)你知道吗

class customer_classes:
    # create the base class
    base = declarative_base(metadata=metadata)

    def __init__(self, metadata, customer_id):

        class analytics(self.base):
            __tablename__ = 'analytics_{}'.format(customer_id)
            __mapper_args__ = ...

        class embeds(self.base):
            __tablename__ = 'analytics_{}'.format(customer_id)
            __mapper_args__ = ...

        class downloads(self.base):
            __tablename__ = 'analytics_{}'.format(customer_id)
            __mapper_args__ = ...

        # now lets assign all these classes to attributes
        import inspect
        defined_classes = [cls for cls in locals().values()
                           if inspect.isclass(cls) and issubclass(cls, base)]
        self.__dict__.update({cls.__name__: cls for cls in defined_classes})

# now we can create a set of classes for customer 123
customer_model = customer_classes(123)
session.query(customer_model. analytics).all()

# you can just as easily work with another customer at the same time in the same session
another_model = customer_classes(456)
session.query(another_model.analytics).all()

相关问题 更多 >