基于restapi中可选字段的SQL Alchemy更新行

2024-04-19 17:49:22 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用sqlalchemy优雅地更新rest端点中可选的选定字段的DB行。你知道吗

假设有一个用户moel:

class User(Base):
        __tablename__ = 'user'
        id = Column(u'id', Integer(), primary_key=True)
        name = Column(u'name', String(50),nullable = False)
        address = Column(u'adress', String(50))
        notes = Column(u'notes', String(50))

示例:我有一个API,它接受可选参数来更新用户数据:

案例1:

  {"id":1,
   "name":"nameone",
   "address":"one address"
}

案例2:这里的地址是可选的

{  "id":1,
   "name":"name-1",
   "notes":"test notes"
}

如果字段已知,我可以使用SQLalchemy更新行

对于案例1:

User.update().where(User.id == id).values(name="nameone",address="one address")

对于案例2:

User.update().where(User.id == id).values(name="name-1",notes="test notes")

有没有什么优雅的方法来代替使用sqlalchemy ORM为每个案例场景编写案例?你知道吗


Tags: 用户nametestidstringsqlalchemyaddressupdate
1条回答
网友
1楼 · 发布于 2024-04-19 17:49:22

使用Python来完成您的逻辑

data = {  "id":1,
   "name":"name-1",
   "notes":"test notes"
}

user = User.query.filter(User.id == data['id']).first()

for attr, val in data.items():
    if not attr == 'id':
        setattr(user, attr, val)

相关问题 更多 >