In SQLAlchemy, how to call a different database tables according to month
<p>In SQLAlchemy, how to call a different database tables according to month.
Each month corresponds to a database table.
I did this, but there was a problem.</p>

<pre><code>Class MyBaseClass (object):
Â Â Â Â  Id = db.Column (db.Integer, primary_key = True)
</code></pre>

<p>In my interface, this is the case</p>

<pre><code>Def test ():
Time = request.get_json (). Get ( 'time')
Tablename = str (time) # time format: such as 201610
Table_object = type (tablename.title (), (MyBaseClass, db.Model), { '__tablename__': tablename})
</code></pre>

<p>The first call to the interface is fine, but if you call it a second time, the following error occurs</p>

<pre><code>Specify 'extend_existing = True' to redefine options and columns on an existing Table object. Sqlalchemy.exc.InvalidRequestError: Table 'xxx' is already defined for this MetaData instance.
</code></pre>

<p>Whether the table can be dynamically built after the table to delete this instance? Because I have to call the second time, will suggest already.</p>

<p>I am an SQLAlchemy beginner and just won exactly the same battle with the ORM framework. Your approach of constructing a new type is on target. You should also look at <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/mixins.html#augmenting-the-base" rel="nofollow">Augmenting the Base</a> manual. Here is <a href="http://stackoverflow.com/questions/39863337/sqlalchemy-orm-with-dynamic-table-schema?noredirect=1#comment67043099_39863337">my solution</a> that combines Base augmentation and dynamic type creation.</p>

<p>I have solved this problem, this but this is NOT how I "won" the fight. Here's my advice: SQLAlchemy ORM is designed to make your life easy, but to take advantage of it you have to align your data in line with ORM expectations. This is what I have done instead of fighting it, and am very happy with the end result.</p>

<p>If, however, you need to stick with historic design or changing it does not make sense, then using ORM will bring more tears than joy and the easy way out is to switch to <a href="http://docs.sqlalchemy.org/en/latest/core/" rel="nofollow">SQLAlchemy Core</a> which is much more flexible and permissive.</p>

python mysql sqlalchemy