当前位置: 代码迷 >> python >> 定义类 sql-alchemy:分配列类型的循环
  详细解决方案

定义类 sql-alchemy:分配列类型的循环

热度:69   发布时间:2023-07-14 08:57:51.0

在为 sql alchemy 定义类时,是否可以避免键入列的名称和数据类型,例如假设您有:

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)

是否可以使用循环重新创建最后一部分? 例如,如果您想将列名和类型作为输入:

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

但是,这会引发 ArgumentError:Mapper Mapper|Fruit|Fruits 无法为映射表“Fruits”组装任何主键列

是否有人能够提供一个工作示例,说明在使用 sql alchemy 时如何将列名和类型用作类定义中的变量?

实际上是的,您可以这样做,但是您需要使用Table()sqlalchemy.orm.mapper创建您的数据库。

你需要做这样的事情:

from sqlalchemy import create_engine, MetaData, Table, Column
from sqlalchemy import Integer, Date # Insert your types here
from sqlalchemy.orm import mapper

engine = create_engine('sqlite:///fruits.db') # Here you need to insert your own path to db

column_names = ['date_of_record', 'number_of_apples', 'number_of_pears']
column_types = [Date, Integer, Integer]

# Adding columns

columns = list()
for index, (name, type) in enumerate(zip(column_names, column_types)):
            if index == 0:   
                columns.append(Column(name, type, primary_key = True))
            else:
                columns.append(Column(name, type))

metadata = MetaData()
fruits_table  = Table('Fruits', metadata, *columns)
metadata.create_all(engine) # Create table

class Fruit(Base):
    # You can make initialization method here
    pass

print(mapper(Fruit, fruits_table)) # Create a Mapper and print it

现在,要进行会话,您需要执行以下操作:

from sqlalchemy.orm import sessionmaker

Session = sessionmaker(bind=engine) # Use an engine with your database
session = Session()

test_fruit = Fruit() # You can initialize it, if you will make __init__ method

test_fruit.number_of_apples = 2
test_fruit.number_of_pears = 3

session.add(test_fruit)
session.commit()

希望我的回答能帮到你!