In the Blender Python API, a collection does not have a direct pointer to its parent collection. However, we can get the parent collection by searching through the list of children of each collection in the scene until we find the current one.
The list of scene collections can be obtained with:
1 2 3 |
bpy.data.collections[:] # [bpy.data.collections['Collection'], bpy.data.collections['Collection 1'], ...] |
But it does not include the top-level scene “Scene Collection” collection. This collection can be obtained with:
1 2 3 |
bpy.context.scene.collection # bpy.data.scenes['Scene'].collection |
Let’s define a full collections list for search:
1 2 |
all_collections = bpy.data.collections[:] all_collections.append(bpy.context.scene.collection) |
The current active collection:
1 |
active_collection = bpy.context.collection |
Now we can find the parent collection for the currently active collection by looking through our list and getting children of each collection. The collection in the children list of which the desired one is found will be the parent for it.
1 2 3 4 5 6 7 |
parent_collection = next((collection for collection in all_collections \ if active_collection.name in collection.children \ ), None) print(parent_collection) # <bpy_struct, Collection("Collection 2") at 0x000001F47C934708> |
If the collection has no parent collection, our method will return None.