Python SqlAlchemy dynamically adds data table field instance parsing, pythonsqlalchemy
This article mainly studies how to dynamically add data table fields in Python SqlAlchemy, as follows.
We know that SqlAlchemy is used to create a class to map data tables. The class attribute is equal to the database field. However, when we create a table, we are not sure about the number of data table fields. How can we solve this problem?
First look at General Usage
From sqlalchemy import create_engine, Column, String, Integerclass Mybase (Base): # Table name__ tablename _ = 'mycars '# field, attribute myid = Column (String (50 ), primary_key = True) price = Column (String (50 ))
The code above is to create a mycars data table. The fields are myid and price, and the number of fields is fixed. To create fields with an ambiguous number, the Code is as follows:
From sqlalchemy import * from sqlalchemy. orm import sessionmakerfrom sqlalchemy. ext. declarative import declarative_baseengine = create_engine ('mysql + pymysql: // root: 1234 @ localhost/test? Charset = utf8', echo = False) # engine = create_engine ('sqlite: // MyDB. sqlite3 ', echo = False) DBSession = sessionmaker (bind = engine) session = DBSession () Base = declarative_base () # define class table_class (Base ): _ tablename _ = 'aaa' id = Column (Integer, primary_key = True) # dynamically Add the field for I in range (3): setattr (table_class, 'col' + str (I), (Column ('col' + str (I), String (50), comment = 'col' + str (I )))) base. metadata. create_all (engine) # add data dt = table_class (Col1 = 'aaa', Col2 = "aaa") session. add (dt) session. commit ()
The code above shows that by usingsetattr()
To dynamically add fields, and the field name can be named according to the actual name. comment is a field annotation, which is only available in SqlAlchemy 1.2.(SqlAlchemy 1.2 installation: pip install-pre sqlalchemy)
Running result:
Of course, when inserting data and querying data, attributes of the corresponding fields in the Code cannot be determined. You can use SqlAlchemy to execute SQL to insert data.
Summary
The above is all the content about how to dynamically Add a data table field instance for parsing in Python SqlAlchemy. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!