0

I am trying to write a function which will take class name a argument and import that class and perform some task.

  def search(**kwargs):
    """
    :return:
    """

    try:
        model = __import__('girvi.models', globals(), locals(),  kwargs['model_name'], -1)
       # Do some task
       return results
    except Exception:
        raise Exception('Model not found')

But thing is model has the class which is in kwargs['model_name'] imported successfully but how do i access it. Please can someone help me.

5
  • It is not working... 'module' object is not callable Commented Oct 18, 2014 at 7:46
  • I am sorry, I still couldn't understand what exactly you are trying to do. Commented Oct 18, 2014 at 7:48
  • If i try this then it is working fine print model.Customer.objects.all() But then whats the point of all of this. Commented Oct 18, 2014 at 7:48
  • @user2217267: that's the point of it. Commented Oct 18, 2014 at 7:49
  • I want to write a function which will take model name and query list generated by operatoras a argument. Then i will perform filter on that model. That can be generic for all of model. Commented Oct 18, 2014 at 7:57

1 Answer 1

1

I would try the following:

import importlib
import sys

def import_class(class_name, module_name = "girvi.models"):
    module = importlib.import_module(module_name)
    class_object = getattr(module, class_name) # does not work for nested classes
    return class_object

According to __import__ one should rather use importlib.import_module.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.