pythongraphene-pythongraphene-django

Is it possible to return a list of Objects for a mutation in graphene?


I've created a mutation to process data in files. These files are represented by a django model called MyModel.

Initially I've taken only one MyModel at a time with his id, but now I've thought that could be better to take a list of MyModel's ids and process them.

So I correct my mutation in this way:

It works fine! But now I want to return the ifile_list (it contains MyModel objects that were processed) and show in graphql console their ID. Is it possible? If yes, how? What should I correct or add? I don't want the solution, but only some concepts that give me the possibility to do that alone.

Thanks in advance, and sorry for bad english!


Solution

  • You can have something like this:

    class ProcessedFile(graphene.ObjectType):
        id = graphene.ID()
        is_processed = graphene.Boolean()
    
    class FileMutation:
        processed_files = graphene.List(
            ProcessedFile,
            incomingfile_list_id=List(ID, required=True)
        )
    
        def resolve_process_file(self, info, incomingfile_list_id, **kwargs):
            try:
                ifile_list = []
                if not incomingfile_list_id:
                    return False
                for id in incomingfile_list_id:
                    ifile_list.append(IncomingFileType.objects(info, "write").get(id=id))
                results = []
                for incomingfile in ifile_list:
                    is_processed = incomingfile.process()
                    # I assume that id can be retrieved
                    results.append(ProcessedFile(id=incomingfile.id, is_processed=is_processed))       
              
            except Exception as e:
                logger.error(f"Error on request to process incoming files from {e}")
                return []
            return results
    

    or using existing IFileType

    class FileMutation:
        processed_files = graphene.List(
            IFileType,
            incomingfile_list_id=List(ID, required=True)
        )
    
        def resolve_process_file(self, info, incomingfile_list_id, **kwargs):
            try:
                ifile_list = []
                if not incomingfile_list_id:
                    return False
                for id in incomingfile_list_id:
                    ifile_list.append(IncomingFileType.objects(info, "write").get(id=id))
                for incomingfile in ifile_list:
                    incomingfile.process()      
            except Exception as e:
                logger.error(f"Error on request to process incoming files from {e}")
                return []
            return ifile_list