Dynamic Table Creation and ORM mapping in SqlAlchemy

前端 未结 7 1858
忘了有多久
忘了有多久 2020-12-23 19:18

I\'m fairly new to using relational databases, so I prefer using a good ORM to simplify things. I spent time evaluating different Python ORMs and I think SQLAlchemy is what

7条回答
  •  半阙折子戏
    2020-12-23 19:37

    If you are looking to create dynamic classes and tables you can use the following technique based from this tutorial URL I found here (http://sparrigan.github.io/sql/sqla/2016/01/03/dynamic-tables.html), I modified how he did it a bit.

    from sqlalchemy import create_engine
    engine = create_engine('sqlite:///test.db', echo=True)
    from sqlalchemy import Column, Integer,Float,DateTime, String, MetaData
    metadata = MetaData()
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    
    Session = sessionmaker(bind=engine)
    session = Session() # create a Session
    Base = declarative_base()
    

    First include all the needed dependencies and create your session and Base.

    The key to creating it dynamically is this here:

    attr_dict = {'__tablename__': 'default','id': Column(Integer, primary_key=True, auto_increment=True)}
    

    you could create a table from just this by taking advantage of the 'type' function in python.

    myClass = type('ClassnameHere', (Base,), attr_dict)

    Note that we are passing in attr_dict, this will give the required tablename and column information to our class, but the difference is we are defining the class name through a string! This means you could create a loop for example going through an array of strings to start creating tables dynamically!

    Next all you have to do is simply call

    Base.metadata.create_all(engine)
    

    Because the dynamic class we created inherits from Base the command will simply create the tables!

    You add to this table for example like this now:

    SomeRow = myClass(id='2')
    session.add(SomeRow)
    session.commit()
    

    This can go even further if you you don't know the column names as well. Just refer to the article to learn how to do that.

    You would essentially do something like this though:

    firstColName = "Ill_decide_later"
    secondColName = "Seriously_quit_bugging_me"
    
    new_row_vals = myClass(**{firstColName: 14, secondColName: 33})
    

    The ** operator takes the object and unpacks it so that firstColName and secondColName are added with assignment operators so it would essentially be the same thing as this:

    new_row_vals = myClass(firstColName=14, secondColName=33)
    

    The advantage of this technique is now you can dynamically add to the table without even having to define the column names!

    These column names could be stored in a string array for example or whatever you wanted and you just take it from there.

提交回复
热议问题