-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..

Stephen K
  • 697
  • 9
  • 26
  • 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. – Ilja Everilä Jul 10 '18 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` – Stephen K Jul 10 '18 at 21:33
  • https://stackoverflow.com/questions/2768607/dynamic-class-creation-in-sqlalchemy – Ilja Everilä Jul 10 '18 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` – mad_ Jul 11 '18 at 13:29

1 Answers1

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..

Stephen K
  • 697
  • 9
  • 26