跨项目重用 SQLAlchemy 模型 [英] Reusing SQLAlchemy models across projects

查看:31
本文介绍了跨项目重用 SQLAlchemy 模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些标准的 SQLAlchemy 模型,可以跨项目重复使用.像这样:

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

我想把它放在一个共享库中并将它导入到每个新项目中而不是剪切和粘贴它,但我不能,因为 declarative_base 实例是在项目.如果有多个,他们将不会共享会话.我该如何解决这个问题?

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?

这是另一个建议使用 mixin 类的问题.那能行吗?SQLAlchemy 会准确地从 mixin 类中导入外键吗?

Here's another question that suggests using mixin classes. Could that work? Will SQLAlchemy accurately import foreign keys from mixin classes?

推荐答案

打电话时

Base = declarative_base()

SA 为此Base 创建新的metadata.

SA create new metadata for this Base.

要重用您的模型,您必须将主要模型的 metadata 绑定到可重用模型,但在任​​何导入可重用模型之前:

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 类可用于重复列声明和扩展类方法.对于基于 MixIns 的connecting 可重用应用程序,您必须在代码中为每个模型手动定义具体类.

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.

SQLAlchemy 会准确导入吗来自 mixin 类的外键?

Will SQLAlchemy accurately import foreign keys from mixin classes?

具有外键和约束的 MixIn 类

MixIn class with foreign key and constraint

from sqlalchemy.schema import UniqueConstraint
from sqlalchemy.ext.declarative import declared_attr

class MessageMixIn(object):
    ttime = Column(DateTime)

    @declared_attr
    def sometable_id(cls):
        return Column(Integer, ForeignKey('sometable.id'))

    @declared_attr
    def __table_args__(cls):
        return (UniqueConstraint('sometable_id', 'ttime'), {})

这篇关于跨项目重用 SQLAlchemy 模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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