Search code examples
pythondjangodispatch

Passing arguments to dispatch methods


  1. I am relatively new to Python and Django.

I am parsing Excel sheets and want to store the data in a DB (MySQL). The information in which table the data is stored is available through the Excel sheet. I'd like to use a dispatch table to decide which Object is stored. The fields needed can vary.

I found something that I hoped would work, but unfortunately does not:

python: dispatch method with string input

func_name_dict = {
    'Assay': Assay.objects.get_or_create()
}

def dispatch(name, *args, **kwargs):
    return func_name_dict[name](**kwargs)

dispatch('Assay', name='ChIP-Seq')

I would hope that the new object would get stored or fetched and returned to the caller.

What seems to happen is that the 3 existing DB records (which all have a different name) are fetched:

website.models.MultipleObjectsReturned: get() returned more than one Assay -- 
it returned 3!

Solution

  • You're calling the method which hi parameters and storing the result in the dict, rather than string the callable method itself. You should do:

    func_name_dict = {
        'Assay': Assay.objects.get_or_create
    }
    

    ie without the parentheses.

    (Although I'm not sure of the point of a dispatch dict like this if you only have one entry.)

    Edit after comment

    Well indeed you have two arguments called name, one as the positional parameter and one in the kwargs. You will need to call the first param something that will never be in the kwargs - for example, dispatch_func_name, or whatever.