英文:
Updating a boolean property in SQLAlchemy(2.x) model while satisfying MyPy
问题
I'm here to provide the translated code portion as you requested:
我正在尝试更新我的SQLAlchemy模型中的布尔属性,并且我希望确保MyPy也满意这段代码。但是,当我尝试更新属性时,MyPy会给我一个错误。这是错误消息:
```python
dashing/db/dao/workspace_dao.py:69: error: 赋值中的类型不兼容
(表达式类型为 "bool",变量类型为 "Column[bool]") [赋值]
workspace.is_archived = new_value
^~~~~~~~~
在 1 个文件中找到 1 个错误(检查了 57 个源文件)
这是我用于更新属性的函数:
async def archive_workspace(
self,
workspace_id: UUID,
new_value: bool,
) -> Optional[WorkspaceModel]:
workspace = await self.session.get(WorkspaceModel, workspace_id)
if workspace is None:
return None
workspace.is_archived = new_value # ← MyPy不喜欢这个赋值
await self.session.commit()
return workspace
这是我的模型定义:
class WorkspaceModel(Base):
__tablename__ = "workspace"
...
is_archived = Column(Boolean, unique=False, default=False)
如何正确更新我的SQLAlchemy模型中的布尔属性,以便MyPy不会引发任何错误?
Please note that the translation may not be exact due to differences in code formatting between English and Chinese, but it conveys the same information.
<details>
<summary>英文:</summary>
I am trying to update a boolean property in my SQLAlchemy model and I want to make sure MyPy is satisfied with the code as well. However, MyPy is giving me an error when I try to update the property. Here's the error message:
dashing/db/dao/workspace_dao.py:69: error: Incompatible types in assignment
(expression has type "bool", variable has type "Column[bool]") [assignment]
workspace.is_archived = new_value
^~~~~~~~~
Found 1 error in 1 file (checked 57 source files)
This is the function I am using to update the property:
```python
async def archive_workspace(
self,
workspace_id: UUID,
new_value: bool,
) -> Optional[WorkspaceModel]:
workspace = await self.session.get(WorkspaceModel, workspace_id)
if workspace is None:
return None
workspace.is_archived = new_value # ← MyPy does not like this assignment
await self.session.commit()
return workspace
And here is my model definition:
class WorkspaceModel(Base):
__tablename__ = "workspace"
...
is_archived = Column(Boolean, unique=False, default=False)
What is the correct way to update the boolean property in my SQLAlchemy model so that MyPy does not raise any errors?
答案1
得分: 1
如@python_user 在他的评论中提到的,我之前在使用旧的语法。使用SQLAlchemy 2.0的语法修复了这个问题:
from sqlalchemy.orm import Mapped, mapped_column
class WorkspaceModel(Base):
__tablename__ = "workspace"
...
is_archived: Mapped[bool] = mapped_column(unique=False, default=False)
英文:
As @python_user mentioned in his comment, I was using old syntax. Using SQLAlchemy 2.0 syntax fixes the issue:
from sqlalchemy.orm import Mapped, mapped_column
class WorkspaceModel(Base):
__tablename__ = "workspace"
...
is_archived: Mapped[bool] = mapped_column(unique=False, default=False)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论