You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用notion-client实现Notion数据库文件路径的条件更新?

问题:Notion数据库条件更新Filepath字段

我有一个存储文件目录列表的Notion数据库,结构为:Filepath | File_name(当前内容正确) | Additional Info。我需要编写脚本完成两个操作:更新本地文件名,同时更新数据库中的Filepath字段以匹配新文件名。

目前已实现从数据库读取File_name和Filepath,传入重命名函数完成本地文件重命名(例如将/example/_test_example.mp4改为/example/example_file.mp4,新文件名来自File_name列),代码如下:

client=Client(auth=NOTION_TOKEN)
db_info=client.databases.retrieve(database_id=files_db)
rows=client.databases.query(database_id=files_db)
content_ids=[]
for row in rows['results']:
    file_name=row['properties']['File_name']['rich_text'][0]['plain_text']
    filepath=row['properties']['Filepath']['title'][0]['plain_text']
    update_filename(file_name,filepath)

这段代码能正常获取数据,重命名函数也能正常工作,但数据库更新函数无法实现“按条件更新对应行”的功能,当前代码:

def update_db(video_file,new_file):    
    client.databases.update({
        "database_id": files_db,
        "properties":{
            'filepath': {'title': [{'text': {'content': filepath}}]},
        }
    })
    pprint('record inserted')

运行时提示缺少数据库ID参数,不清楚如何用notion-client实现类似update x where y=y的条件更新,请求可行的示例代码。


解决方案

核心问题说明

  • client.databases.update()是用来修改数据库本身的配置(比如属性结构),不是更新数据库里的行记录;要更新单条记录,必须用client.pages.update()
  • 实现“条件更新”的核心是获取每行记录的唯一page_id,用它定位要修改的行(相当于SQL里的主键)

完整可行代码示例

from notion_client import Client
import pprint
import os

client = Client(auth=NOTION_TOKEN)
files_db = "你的数据库ID"

def update_filename(new_name, old_filepath):
    # 本地文件重命名逻辑
    dir_path = os.path.dirname(old_filepath)
    new_filepath = os.path.join(dir_path, new_name)
    os.rename(old_filepath, new_filepath)
    return new_filepath

def update_db(page_id, new_filepath):    
    # 更新指定行的Filepath字段
    client.pages.update(
        page_id=page_id,
        properties={
            'Filepath': {  # 属性名需与Notion数据库完全一致(区分大小写)
                'title': [{'text': {'content': new_filepath}}]
            }
        }
    )
    pprint('记录已更新')

# 遍历数据库并执行更新流程
rows = client.databases.query(database_id=files_db)
for row in rows['results']:
    # 获取当前行的唯一ID(关键)
    page_id = row['id']
    # 读取当前行的文件名与旧路径
    file_name = row['properties']['File_name']['rich_text'][0]['plain_text']
    old_filepath = row['properties']['Filepath']['title'][0]['plain_text']
    
    # 执行本地重命名,得到新路径
    new_filepath = update_filename(file_name, old_filepath)
    
    # 更新数据库对应行的Filepath
    update_db(page_id, new_filepath)

关键注意点

  1. 必须通过row['id']获取每条记录的page_id,这是定位行的唯一标识
  2. 属性名要和Notion数据库中的名称完全匹配(比如数据库里是Filepath,代码里不能写成小写的filepath)
  3. client.pages.update()的参数是page_id,而非database_id

内容的提问来源于stack exchange,提问作者Cool Spot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 08:26:16