我正在构建应用程序并使用 FastApi 进行 API 开发,但是,我可以创建(通过手动定义 ORM 基础模型和模式模式)
但我想要一种情况,该模型定义来自我已经在那里定义的数据库。
如何从数据库动态生成pydantic基础模型和模式模型
我真的需要帮助。
// at the moment my post schema is like this
class Post(BaseModel):
id: int
title: str
content: str
postdate: str
// and my ORM model is like this
class Post(Base):
__tablename__ = "posts"
# Defining Colums
id = Column(Integer, primary_key=True, nullable=False)
title = Column(String, nullable=False)
content = Column(String, nullable=False)
postdate= Column(TIMESTAMP(timezone=True),
nullable=False, server_default=text('now()'))
// what i want now is to dynamically generate the model fields from database. because it would be already created there.
example
class Post(BaseModel):
// this should be populated here from database
// and my ORM model is like this
class Post(Base):
__tablename__ = "posts"
# Defining Colums
// this should be populated here from database
pydantic-db
直接从数据库模式生成 Pydantic 模型。
pydantic-db generate \
--db-url mysql://user:password@localhost:5432/dbname \
--output models.py
然后运行
pydantic-db generate --config pydantic-db.yml