使用 Office365-REST-Python-Client 创建 SharePoint 列表时,如何在 ListCreationInformation 对象中指定字段列表?

How do I specify a list of fields in a ListCreationInformation object, when using Office365-REST-Python-Client to create a SharePoint List?

我想创建一个与现有列表具有相同字段的新列表。

我可以获取现有列表的字段,并且我找到了许多使用此库创建列表的示例:

但是 none 这些帮助我理解了如何从具有非模板字段的现有列表中正确构造 ListCreationInformation 对象。

这是我目前的情况:

from office365.sharepoint.client_context import ClientContext
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.lists.list_creation_information import ListCreationInformation
from office365.sharepoint.lists.list_template_type import ListTemplateType

# placeholders for my actual details
username = input()
password = input()
url = 'https://company.sharepoint.com/sites/Existing%20Site'
old_list_name = 'Existing%20List'
new_list_name = 'New%20List'

# authenticate and get a context object
ctx_auth = AuthenticationContext(url)
if ctx_auth.acquire_token_for_user(username, password):
    ctx = ClientContext(url, ctx_auth)
    web = ctx.web
    ctx.load(web)
    ctx.execute_query()
    print("Connected to SharePoint Site: {0}".format(web.properties['Title']))
else:
    print(ctx_auth.get_last_error())

# get field names from the old list
sp_existing_list = ctx.web.lists.get_by_title(old_list_name)
old_fields = sp_existing_list.fields
ctx.load(old_fields)
ctx.execute_query()

# define the new list
lci = ListCreationInformation()
lci.BaseTemplate = ListTemplateType.GenericList
lci.Title = new_list_name
lci.AllowContentTypes = true
#
# what do I need here, to add the old list field details?
#

# create the new list
sp_new_list = ctx.web.lists.add(lci)
ctx.execute_query()

# add an item from the old list to the new list to confirm
items = sp_existing_list.get_items()
ctx.load(items)
ctx.execute_query()
sp_new_list.add_item(items[0].properties)
ctx.execute_query()

运行 此代码按原样(未指定 ListCreationInformation 对象中的额外字段)在最后一行产生 ClientRequestException,形式为:

ClientRequestException: ('-1, Microsoft.SharePoint.Client.InvalidClientQueryException', "The property 'missing_field_name' does not exist on type 'SP.Data.New_x0020_ListListItem'. Make sure to only use property names that are defined by the type.", "400 Client Error: Bad Request for url: https://company.sharepoint.com/sites/Existing%20Site/_api/Web/lists/GetById('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx')/items")

虽然已创建列表,并且已检索旧列表中的项目以插入到新列表中,但显然 missing_field_name 字段不存在。

如何使用旧字段名称更新 ListCreationInformation 对象?

您可以像这样将自定义字段添加到列表中

from office365.sharepoint.fields.field_creation_information import FieldCreationInformation

custom_field  = FieldCreationInformation('my_custom_field', field_type_kind=FieldType.Text)
sp_new_list.fields.add(custom_field)

您可以遍历 old_fields 列表并将它们添加到新列表中。

如果您想让 my_custom_field 在新列表的默认视图中可见:

sp_new_list.default_view.view_fields.add_view_field('my_custom_field')