Django get class from string
Question: I'm looking for a generic way in Python to instantiate class by its name in
similar way how it is done in Java without having to explicitly specify the
class name in IF..ELIF condition.

This is because I have several different models and serializers and want to
make them addressable by parameters in the HTTP request. It is to enhance
loose coupling and modularity.

For example `https://www.domain.com/myapp/sampledata.json?model=<modelname>`
should get the classes `<modelname>` and `<modelname>Serializer`.

There are some changes to this since Django 1.7
`https://docs.djangoproject.com/en/1.7/ref/models/queries/`, before
`get_model` was used for similar purpose.

> As of Django 1.7 the django.db.models.loading is deprecated (to be removed
> in 1.9) in favor of the the new application loading system.

The warning:

> RemovedInDjango19Warning: The utilities in django.db.models.loading are
> deprecated in favor of the new application loading system.  
>  return f(*args, **kwds)

How should the following code be modified to get class from string?

views.py

    
    
    from myapp.models import Samplemodel, Simplemodel1, Simplemodel2
    from myapp.serializers import SamplemodelSerializer, Simplemodel1Serializer, Simplemodel2Serializer
    from django.db.models.loading import get_model # deprecated
    from myapp.jsonp_decorator import json_response
    
    @json_response
    def sampledata(request):
    
        model = request.GET.get('model','Samplemodel')
    
        if model=='Samplemodel':
            modelName = "Samplemodel"
            serializer = SamplemodelSerializer
        elif model=='Simplemodel1':
            modelName = "Simplemodel1"
            serializer = Simplemodel1Serializer
        elif model=='Simplemodel2':
            modelName = "Simplemodel2"
            serializer = Simplemodel2Serializer
    
        return serializer(get_model("myapp",modelName).objects.all(), many=True)  
    


Answer: You could use `getattr`:

    
    
    import my_serializers
    
    serializer_class = getattr(my_serializers, 'SimpleSerializer')
    serializer = serializer_class()
    

