在短片中,session.Query(User).all()
返回用户对象的列表。我想在相同的级别上进行session.add_colums()
,但是失败了。
原样
{
"User": {
"name": "John",
"age": 20
},
"department_name": "Apple"
}
准-
{
"name": "John",
"age": 20
"department_name": "Apple"
}
我正在使用FastAPI和SQLAlchemy。
我想用它的部门名称来响应连接结果,例如User。
# SQLAlchemy Models
class User(Base):
id = Column(Intger, primary_key=True)
name = Column(String)
age = Column(Integer)
department_id = Column(Integer, ForeignKey("department.id"), nullable=False)
class Department(Base):
id = Column(Intger, primary_key=True)
name = Column(String)
UserDetail是FastAPI中用于反应模型的化脓性模型。
# Pydantic Model
class UserDetail(BaseModel):
name: str
age: int
department_name: str
class Config:
orm_mode = True
# FastAPI path operation function
@app.get("/users")
def read_users():
q = session.query(User).join(Department).set_label_style(LABEL_STYLE_DISAMBIGUATE_ONLY)
# set label style: use column name without its table name
q.add_column(Department.name).label('department_name') # I want to add
return q.all()
然后返回如下:
[{
"User": {
"name": "John",
"age": 20
},
"department_name": "Apple"
}]
如何将其改为化脓性模型?如果我只是添加响应模型,它就会引发ValidationError。
[{
"name": "John",
"age": 20,
"department_name": "Apple"
}]
我不想详细地查询User.name和User.age,因为可以更改pydantic模型或SQLAlchemy模型。
我想把它们都装上。
发布于 2022-09-25 16:59:02
SQLAlchemy有两种模式: Core和ORM (What is the difference between SQLAlchemy Core and ORM?)
如果我希望获得ORM服从get的查询,我应该使用query(Model)
来使用SQLAlchemy ORM。
但是如果我只想得到列,我必须使用query(Model.__table__)
https://stackoverflow.com/questions/73822928
复制相似问题