Django get class from string

心已入冬 提交于 2020-01-06 11:34:13

问题


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)  

回答1:


You could use getattr:

import my_serializers

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



回答2:


The best way to allow dynamic class loading in this case is:

from myapp import models
from myapp import serializers
from myapp.jsonp_decorator import json_response

@json_response
def sampledata(request):

    model = request.GET.get('model','Samplemodel')
    serializer_class = getattr(serializers, model+"Serializer")
    return serializer_class(getattr(models,modelName).objects.all(), many=True)


来源:https://stackoverflow.com/questions/34016770/django-get-class-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!