Python Sqlalchemy-表名作为变量 [英] Python Sqlalchemy - tablename as a variable

查看:573
本文介绍了Python Sqlalchemy-表名作为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Python中使用SQLAlchemy,并声明我的类从声明式基础继承,如下所示:

I am using SQLAlchemy in Python and am declaring my classes inheriting from a declarative base as follows:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class SomeClass(Base):
    __tablename__ = 'some_table'
    id = Column(Integer, primary_key=True)
    name =  Column(String(50))

作为用户,我想将__tablename__定义为参数,而不是硬编码值,如下所示:

As a user I would like to define the __tablename__ as a parameter, and not a hard-coded value , something like this:

class SomeClass(Base):
    __tablename__ = f'{environment}_some_table'
    id = Column(Integer, primary_key=True)
    name =  Column(String(50))

据我了解,导入此软件包时将对f'{environment}_some_table'进行评估,因此以后将无法对其进行修改(即在交互式笔记本中).我有一段破碎的代码试图通过嵌套类和封装来解决这个问题,但是我没有设法引用外部类的实例变量.

It is my understanding that f'{environment}_some_table' will be be evaluated when I import this package, and therefore I won't be able to modify it at a later stage (i.e. in an interactive notebook). I have a broken piece of code that tries to solve this through nested classes and encapsulation, but I do not manage to reference the instance variable of an outer class.

class Outer:
    def __init__(self, env):
        self.environment = env

    class SomeClass(Base):
        __tablename__ = f'{self.environment}_some_table'
        id = Column(Integer, primary_key=True)
        name =  Column(String(50))

我已经阅读了几个SO问题,最好不要使用嵌套类,因为在这些类之间没有建立特殊的关系. 那么我应该使用哪种设计来解决这个问题?

I have read in a couple of SO questions that it is better not to use nested classes since no special relationship is established between these classes. So what kind of design should I use to solve this problem?

提前谢谢!

推荐答案

您可以在函数范围内创建所有模型定义,因此依赖于外部参数:

you can make all your model definitions inside a function scope so the will be depended on outer arguments:

def create_models(environment):
    class SomeClass(Base):
        __tablename__ = f'{environment}_some_table'
        id = Column(Integer, primary_key=True)
        name =  Column(String(50))
    ...
    globals().update(locals()) # update outer scope if needed

... # some time later
create_models('cheese')
... # now create the db session/engine/etc ... 

要查看的另一种选择是内置的 reload 方法.检查一下:)

another choice to look at is the builtin reload method. check it out :)

这篇关于Python Sqlalchemy-表名作为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆