【问题标题】:Using SQLAlchemy mappings with variant tables将 SQLAlchemy 映射与变体表一起使用
【发布时间】:2016-01-07 02:33:33
【问题描述】:

我有一个用于所有客户的数据库。每个客户都有一组表,后缀是他们的客户 ID:

  • analytics_123
  • embeds_123
  • downloads_123

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

我更喜欢使用声明式语法,但有什么方法可以动态设置模型的__tablename__ 值?如果我需要在线程环境中访问多个客户,会发生什么情况(我们很可能会使用不同的进程,但我宁愿预先覆盖它以防万一)。

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

【问题讨论】:

  • 考虑使用单独的数据库或模式,而不是后缀表。

标签: python sqlalchemy


【解决方案1】:

一种方法是为客户提供您需要的所有类。类似于以下内容......(这只是一个草图!)

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

【讨论】:

  • 感谢您的输入 - 不是 100% 肯定我会使用这个确切的模型,但类似的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-20
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
  • 1970-01-01
  • 2016-05-13
  • 2020-05-15
相关资源
最近更新 更多