跨项目重用 SQLAlchemy 模型
我有一些在项目中重复使用的标准 SQLAlchemy 模型。像这样的事情:
from sqlalchemy import Column, Integer, String, Unicode
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Category(Base):
__tablename__ = 'category'
id = Column(Integer, primary_key=True)
slug = Column(String(250), nullable=False, unique=True)
title = Column(Unicode(250), nullable=False)
def __call__(self):
return self.title
我想将其放入共享库中并将其导入到每个新项目中,而不是剪切和粘贴它,但我不能,因为 declarative_base
实例是在该项目。如果有多个会话,他们将不会共享会话。我该如何解决这个问题?
这是另一个建议使用 mixin 类的问题。那行得通吗? SQLAlchemy 能否准确地从 mixin 类导入外键?
I have some standard SQLAlchemy models that I reuse across projects. Something like this:
from sqlalchemy import Column, Integer, String, Unicode
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Category(Base):
__tablename__ = 'category'
id = Column(Integer, primary_key=True)
slug = Column(String(250), nullable=False, unique=True)
title = Column(Unicode(250), nullable=False)
def __call__(self):
return self.title
I'd like to put this in a shared library and import it into each new project instead of cutting and pasting it, but I can't, because the declarative_base
instance is defined separately in the project. If there's more than one, they won't share sessions. How do I work around this?
Here's another question that suggests using mixin classes. Could that work? Will SQLAlchemy accurately import foreign keys from mixin classes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您调用
Base = declarative_base()
SA 时,为此
Base
创建新的元数据
。要重用模型,您必须将主模型的元数据绑定到可重用模型,但在导入可重用模型之前,可以通过以下方式:
Base.metadata = my_main_app.db.metadata
MixIn 类对于重复列声明和扩展类方法很有用。
对于基于 MixIn 的
连接
可重用应用程序,您必须在代码中为每个模型手动定义具体类。具有外键和约束的 MixIn 类
When you call
Base = declarative_base()
SA create new
metadata
for thisBase
.To reuse your models you must bind
metadata
of main models to reusable models, but before any import of your reusable models by:Base.metadata = my_main_app.db.metadata
MixIn classes useful for repeating column declarations, and extending class methods.
For
connecting
reusable apps based on MixIns you must define concrete class in code manualy for each model.MixIn class with foreign key and constraint