-1

I have a tuple of data:

('dave', 23, 'm'),
('alice', 33, 'f'),
('mary', 44, 'f')

I have an sqlalchemy base class:

class People(Base):
    __tablename__='people'

I want to be able to dynamically create columns/fields for this class using data from the tuple above

the end result would be:

class People(Base):
    __tablename__='people'

    dave = Column(String)
    alice = Column(String)
    mary = Column(String)

though, i can't figure out how do use the splat operator to create the fields..

4
  • Usually you'd have name, age, and sex columns instead in your people table, and you'd store the tuples as rows of that table. Commented Jul 10, 2018 at 21:30
  • my example was poor. i have an excel doc with column_name,type and i want to be able to dynamically create columns like col['column_name'] = Column(col['type']) for col in columns Commented Jul 10, 2018 at 21:33
  • stackoverflow.com/questions/2768607/… Commented Jul 10, 2018 at 21:35
  • You can create table with dynamic fields and then map to one of the ORM class.https://stackoverflow.com/questions/2574105/sqlalchemy-dynamic-mapping/2575016#2575016 Commented Jul 11, 2018 at 13:29

1 Answer 1

0

The solution -

edtl_schematic = {
    '__tablename__': 'fedex_shipments'
}

for c in cols:
    (column, db_name, db_type) = c
    edtl_schematic[c[1]] = Column(db_name, eval(db_type),primary_key=True if db_name=='ship_trk_num' else False)


ExtendedShipmentDetail=type('ExtendedShipmentDetail',(Base,),edtl_schematic)
Base.metadata.create_all(engine)

cols is a tuple that contains information loaded from an excel sheet that has the columns Sheet Column | DB Name | DB Type where DB Name is the name i want the excel sheet column to have in the DB, and DB Type is a sqlalchemy type. Whether this is the correct way of doing this or not, it works..

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.