【问题标题】:How to get the rows of a database in the order in which they're displayed?如何按显示顺序获取数据库的行?
【发布时间】:2021-08-23 11:48:28
【问题描述】:

我有一些 Python 代码使用 notion-client library 检索 Notion 数据库中的行。该代码确实设法检索所有行,但顺序错误。我查看了 API 参考中的Sort object,但无法弄清楚如何使用它以它们在 notion.so 上显示的确切顺序返回行。这是有问题的sn-p:

from notion_client import Client

notion = Client(auth=NOTION_API_TOKEN)
result = notion.databases.query(database_id='...')
for row in result['results']:
  title = row['properties']['NAME_OF_PROPERTY']['title']
  if len(title) == 0:
    print('')
  else:
    print(title[0]['plain_text'])

我错过了什么?

【问题讨论】:

    标签: python notion-api


    【解决方案1】:

    这和他们的documentation 一样有效

    const response = await notion.databases.query({
        database_id: databaseId,
        filter: {
          or: [
            {
              property: 'In stock',
              checkbox: {
                equals: true,
              },
            },
            {
              property: 'Cost of next trip',
              number: {
                greater_than_or_equal_to: 2,
              },
            },
          ],
        },
        sorts: [
          {
            property: 'Last ordered',
            direction: 'ascending',
          },
        ],
      });
    

    【讨论】:

      【解决方案2】:

      Notion API 不支持当前版本中的视图,因此它不一定会匹配您拥有它的顺序,除非您应用了也可以通过 API 应用的排序或过滤器。

      【讨论】:

        【解决方案3】:

        notion.databases.query() 使用order 参数。此参数是排序规范的列表,它们是字典。

        result = notion.databases.query(
            database_id = 'df4dfb3f-f36f-462d-ad6e-1ef29f1867eb',
            sort = [{"property": "NAME_OF_PROPERTY", "direction": "ascending"}]
        )
        

        您可以在列表中放置多个排序规范,后面的将用于前面属性中相等的行。

        【讨论】:

        • 是的,我试过这个,但我应该为“财产”添加什么?我不想按任何特定属性(列)排序,我只想按它们在表中出现的顺序排序。就我而言,在表格中添加与显示顺序相对应的另一列是不切实际的。
        • 在关系数据库中,表没有顺序。如果您希望结果按特定顺序排列,则需要指定顺序。
        • @Barmar 通常适用于关系数据库,这是真的,但在 Notion 视图中,(如果没有设置排序)您可以手动拖动项目以进行自定义排序。我猜这与视图一起存储在内部某个地方,并且由于 API 限制,目前无法查询视图(根据adlopez15 的回答)。
        猜你喜欢
        • 2016-07-10
        • 2014-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-03
        • 1970-01-01
        • 2021-09-10
        • 2020-02-16
        相关资源
        最近更新 更多