How to save file on storage and add to child_entity?

Hi,

I have a case where Excel-files are returned from a generic worker. Those files I want to add as child entities and store on storage.

I know how to create the child entities by the following method:

entity = API().get_entity(entity_id)
child_entity = entity.create_child(
    entity_type_name="xxx",
    name="xxx",
)

And I know how to store the file on storage by the following method:

storage.set(
    key=child_entity.name,
    data=File.from_data(output_file.read()),
    scope="entity",
    entity=child_entity,
)

But I don’t know how to connect the two methods, so the file is added correct to the child_entity. By using the above method for storage.set (using entity=child_entity), no file is added to child_entity.

I didn’t find any solution to my problem in the VIKTOR documentation, so I hope someone here can help.

Hi Mads!

Welcome to the community forum :smiley:.
I tested a similar functionality in a test app, and I could make it work.

I defined two entities.

Parent entity:

from viktor import ViktorController
from viktor.api_v1 import API
from viktor.core import Storage, File
from viktor.parametrization import ViktorParametrization, ActionButton


class Parametrization(ViktorParametrization):
    calculation_btn = ActionButton("create entity with storage", "create_entity")

class Controller(ViktorController):
    label = 'My Folder'
    children = ['MyEntityType']
    show_children_as = 'Table'
    parametrization = Parametrization

    def create_entity(self, entity_id, **kwargs):
        entity = API().get_entity(entity_id)
        child_entity = entity.create_child(
            entity_type_name="MyEntityType",
            name="test",
            params={}
        )
        Storage().set(
            key=child_entity.name,
            data=File.from_data("hello"),
            scope="entity",
            entity=child_entity,
        )

Child entity:

from viktor import ViktorController
from viktor.core import Storage
from viktor.parametrization import ViktorParametrization, ActionButton


class Parametrization(ViktorParametrization):
    calculation_btn = ActionButton("Get file", "get_from_storage")


class Controller(ViktorController):
    viktor_enforce_field_constraints = True

    label = 'My Entity Type'
    parametrization = Parametrization

    def get_from_storage(self, **kwargs):
        file = Storage().get(
            key="test",
            scope="entity",
        )
        print(file.getvalue())

The child entity is created successfully and a file is stored on the child entity.
Have you upgraded your SDK version with viktor-cli upgrade and is the content of the stored file valid?

Let me know if you still get stuck.