sqlalchemy根据字典kv自定义表结构
根据数据的内容自动创建数据库表结构
from sqlalchemy import create_engine, Column, Integer, String, Float, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Mapped, mapped_column
Base = declarative_base()
def create_model_from_dict(model_name, data_dict):
class_attributes = {"__tablename__": model_name.lower()}
class_attributes['id'] = mapped_column(Integer, primary_key=True)
for key, value in data_dict.items():
if isinstance(value, int):
class_attributes[key] = mapped_column(Integer)
elif isinstance(value, str):
class_attributes[key] = mapped_column(String)
elif isinstance(value, float):
class_attributes[key] = mapped_column(Float)
elif isinstance(value, bool):
class_attributes[key] = mapped_column(Boolean)
else:
raise ValueError(f"Unsupported type for column {key}")
model_class = type(model_name, (Base,), class_attributes)
return model_class
# 示例字典
data = {
'name': 'Alice',
'age': 30,
'height': 1.65,
'is_active': True
}
# 创建模型
User = create_model_from_dict('User', data)
# 创建数据库引擎
engine = create_engine('sqlite:///example.db', echo=True)
# 创建表
Base.metadata.create_all(engine)
# 创建会话
Session = sessionmaker(bind=engine)
session = Session()
# 创建一个新的 User 对象
new_user = User(**data)
# 将新用户添加到会话中
session.add(new_user)
# 提交会话以保存更改
session.commit()
print("User added successfully.")
出处: https://www.cnblogs.com/meizhengchao/p/18260680
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接 如有问题, 可邮件(meizhengchao@qq.com)咨询.