Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy, using the same model with multiple tables

I have data for a particular entity partitioned across multiple identical tables, often separated chronologically or by numeric range. For instance, I may have a table called mytable for current data, a mytable_2013 for last year's data, mytable_2012, and so on.

Only the current table is ever written to. The others are only consulted. With SQLAlchemy, is there any way I can specify the table to query from when using the declarative model?

like image 400
Pedro Werneck Avatar asked Aug 22 '14 16:08

Pedro Werneck


People also ask

How do you join 2 tables using SQLAlchemy?

DEBUG) Base = declarative_base() class table_1(Base): __tablename__ = 'table_1' ID = Column(Integer) FIRST_NAME = Column(String(80),primary_key = True) LAST_NAME = Column(String(80)) class table_2(Base): __tablename__ = 'table_2' ID_1 = Column(Integer) FIRST_NAME_1 = Column(String(80),primary_key = True) LAST_NAME_1 = ...

Is there something better than SQLAlchemy?

Django, Pandas, Entity Framework, peewee, and MySQL are the most popular alternatives and competitors to SQLAlchemy.

Is SQLAlchemy deprecated?

Deprecated since version 0.7: As of SQLAlchemy 0.7, the new event system described in Events replaces the extension/proxy/listener system, providing a consistent interface to all events without the need for subclassing.

Should I use SQLAlchemy core or ORM?

If you want to view your data in a more schema-centric view (as used in SQL), use Core. If you have data for which business objects are not needed, use Core. If you view your data as business objects, use ORM. If you are building a quick prototype, use ORM.


2 Answers

Use mixins and change table names by an object property.

class Node(Base):
  __tablename__ = 'node'
  nid = Column(Integer, primary_key=True)
  uuid = Column(String(128))
  vid = Column(Integer)

class Node1(Node):
  __tablename__ = 'node_1'

class Node2(Node):
  __tablename__ = 'node_2'
like image 88
Victor Shelepen Avatar answered Sep 22 '22 06:09

Victor Shelepen


As requested, re-posting as answer:

Please take a look at this answer to Mapping lots of similar tables in SQLAlchemy in the Concrete Table Inheritance section.
In your case you can query MyTable only when working with the current data, and do a polymorphic search on all tables when you need the whole history.

like image 5
van Avatar answered Sep 21 '22 06:09

van