Django从字符串获取类 [英] Django get class from string
问题描述
我正在寻找一种通用的Python方式,以类似于Java的方式通过名称实例化类,而不必在IF..ELIF条件下明确指定类名称。
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.
这是因为我有几种不同的模型和序列化器,并希望通过HTTP请求中的参数使它们可寻址。
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.
例如 https://www.domain.com/myapp/sampledata.json?model= < modelname>
应该获得类< modelname>
和< modelname> Serializer
。
自Django 1.7 https://docs.djangoproject.com/en/1.7/ref/models/起query /
,在 get_model
用于类似目的之前。
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.
从Django 1.7开始,不推荐使用django.db.models.loading(在1.9中将
删除),而是使用新的应用程序加载系统。
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.
警告:
RemovedInDjango19警告:django.db.models.loading $ b中的实用程序为支持新的应用程序加载系统,已弃用$ b。
返回f(* args,** kwds)
RemovedInDjango19Warning: The utilities in django.db.models.loading are deprecated in favor of the new application loading system.
return f(*args, **kwds)
如何修改以下代码以从stri获取类ng?
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)
推荐答案
ngo 3+
获取模型实例的通用方法:
for Django 3+ the universal way to get the model instance:
def get_data_instance(model_name):
"""
Try to find application with name "data" with specific "model_name"
:param model_name: the name of the class
:return: model instance or None
"""
try:
app_config = apps.get_app_config('data')
return app_config.get_model(model_name)
except LookupError:
pass
return None
这篇关于Django从字符串获取类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!