Reusing SQLAlchemy Models for Different Projects

I have standard SQLAlchemy models that I use for different projects. Something like that:

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 would like to put this in a shared library and import it into each new project instead of cutting and pasting it, but I cannot, because the declarative_base instance is defined separately in the project. If there are more than one, they will not use sessions. How do I get around this?

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

+6
source share
1 answer

When you call

Base = declarative_base()

SA create a new metadata for this Base .

To reuse your models, you must bind the metadata main models to reusable models, but before any import of your reusable models:

Base.metadata = my_main_app.db.metadata

MixIn classes are useful for repeating column declarations and extending class methods. For connecting applications for reuse based on MixIns, you must define a specific class in the code manual for each model.

Will SQLAlchemy accurately import foreign keys from mixin classes?

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'), {}) 
+3
source

Source: https://habr.com/ru/post/886814/


All Articles