How to get the rows of a database in the order in which they're displayed?

Viewed 1626

I have some Python code that retrieves the rows in a Notion database using the notion-client library. The code does manage to retrieve all the rows, but the order is wrong. I looked at the Sort object from the API reference, but was unable to figure out how to use it to return the rows in the exact order in which they're displayed on notion.so. Here's the snippet in question:

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'])

What am I missing?

3 Answers

The Notion API does not support views in the current version, so it is not necessarily going to match the order you have it in unless you have applied a sort or filter that you can also apply via the API.

This is working as well as their 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',
      },
    ],
  });

Use the order argument to notion.databases.query(). This argument is a list of sort specifications, which are dictionaries.

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

You can put multiple sort specifications in the list, the later ones will be used for rows that are equal in the preceding properties.

Related