Is it possible to avoid typing out names and datatypes of columns when defining a class for sql alchemy, for example suppose you have:
from sqlalchemy import Column, Date, Integer, String, Numeric
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Fruit(Base):
__tablename__ = 'Fruits'
# names and datatypes of columns
date_of_record = Column(Date, primary_key=True)
number_of_apples = Column(Integer)
number_of_pears = Column(Integer)
Is it possible to recreate this last section using a loop? For example if you wanted to have the column names and types as an input:
column_names = ['date_of_record', 'number_of_apples', 'number_of_pears']
column_types = [Date, Integer, Integer]
class Fruit(Base):
__tablename__ = 'Fruits'
def __init__(self, column_names, column_types):
for index, (name, type) in enumerate(zip(column_names, column_types)):
if index == 0:
setattr(self, name, Column(type, primary_key = True))
else:
setattr(self, name, Column(type))
However this throws an ArgumentError: Mapper Mapper|Fruit|Fruits could not assemble any primary key columns for mapped table 'Fruits'
Is anyone able to provide a working example of how you can use column names and types as variables in class definition when using sql alchemy ?
class
statement block (you can check SQLAlchemy source code to find out why), AND this is a very bad idea anyway wrt/ readabilty / maintainability. – bruno desthuilliersTable
objects easily, or even the light weighttable()
constructs. – Ilja Everilä