Skip to content

Commit

Permalink
更新笔记于 2023-12-08_16:48:45
Browse files Browse the repository at this point in the history
  • Loading branch information
moyechen committed Dec 8, 2023
1 parent a48e4f5 commit f109778
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
72 changes: 72 additions & 0 deletions python/python可变对象在sqlalchemy中的问题.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# python可变对象在sqlalchemy中的问题


## 问题
sqlalchemy 在处理可变对象时,如果可变对象地址没有变化,不会触发更新


```python

repo = session_maker

async def test_edit_fields(
self, engine,init_app_page_extractions
):
repo = container.repo()
async with repo.new_session() as session, session.begin():
result = await repo.session.execute(select(PageCommandOrm))
pages = result.scalars().all()
for row in pages:
print(row.edit_fields)
row.edit_fields["ff"] = 1


repo.session.add_all(pages)

async with repo.new_session() as session, session.begin():
session.flush()
result = await repo.session.execute(select(PageCommandOrm))
pages = result.scalars().all()
for row in pages:
print(row.edit_fields)

```

输出如下
```
{}
{}
{}
{}
{}
{}
```

在上面的例子中,`row.edit_fields["ff"] = 1` 这样的操作不会修改edit_fields 这个变量的地址,因此sqlalchemy认为未修改该字段,不会更新该字段

`row.edit_fields = {"ff":1}` 修改了,触发了更新


## 解决方案

使用官方提供的方法`flag_modified`

```
from sqlalchemy.orm.attributes import flag_modified
async def test_edit_fields(
self, engine, init_app_page_extractions
):
repo = container.repo()
async with repo.new_session() as session, session.begin():
result = await repo.session.execute(select(PageCommandOrm))
pages = result.scalars().all()
for row in pages:
print(row.edit_fields)
row.edit_fields["ff"] = 1
flag_modified(row, "edit_fields") # 标记该字段需更新
repo.session.add_all(pages)
```
10 changes: 10 additions & 0 deletions python/vx.json
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,16 @@
"signature": "207324052537419",
"tags": [
]
},
{
"attachment_folder": "",
"created_time": "2023-12-08T07:18:13Z",
"id": "181",
"modified_time": "2023-12-08T08:48:35Z",
"name": "python可变对象在sqlalchemy中的问题.md",
"signature": "207324068365109",
"tags": [
]
}
],
"folders": [
Expand Down
Binary file modified vx_notebook/notebook.db
Binary file not shown.

0 comments on commit f109778

Please sign in to comment.