Django从字符串中获取类

时间:2015-12-01 09:22:59

标签: generics django-models generic-programming django-1.8 django-serializer

我正在寻找Python中的通用方法,通过其名称实例化类,就像在Java中完成它一样,而不必在IF..ELIF条件中明确指定类名。

这是因为我有几个不同的模型和序列化器,并希望通过HTTP请求中的参数使它们可寻址。它是为了增强松耦合和模块化。

例如https://www.domain.com/myapp/sampledata.json?model=<modelname>应该获得课程<modelname><modelname>Serializer

自从https://docs.djangoproject.com/en/1.7/ref/models/queries/用于类似目的之前,Django 1.7 get_model以来对此进行了一些更改。

  

从Django 1.7开始,不推荐使用django.db.models.loading(将...   在1.9)中删除了有利于新的应用程序加载系统。

警告:

  

RemovedInDjango19Warning:django.db.models.loading中的实用程序   不赞成使用新的应用程序加载系统   return f(* args,** kwds)

如何修改以下代码以从字符串中获取类?

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)  

3 个答案:

答案 0 :(得分:1)

您可以使用getattr

import my_serializers

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

答案 1 :(得分:1)

对于Django 3+ 获取模型实例的通用方法:

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

答案 2 :(得分:0)

在这种情况下允许动态类加载的最佳方法是:

<table id="motionsTable" summary="This table is an index of all papers">
  <thead>
    <tr>
      <!--<th>&nbsp;</th> -->
      <th scope="col">Task </th>
      <th scope="col">Event</th>
      <th scope="col">Date</th>
      <th scope="col">person</th>
      <th scope="col">result</th>

    </tr>
  </thead>
  <tbody>
    <tr>
      <td>lkdjf dpfj dlkfkhg pldfjk;l</td>
      <td>ojkdfh dsfkjh</td>
      <td>August 29, 2013</td>
      <td>
        August 29, 2013 jlkfdj</td>
      <td>James Bradley gfhf;lmk fglkjm ;ldf;ljgk ;dlfjkgd</td>
    </tr>
    <tr>
      <td>fgh</td>
      <td>fghfg</td>
      <td>August 29, 20136 787899 990 000</td>
      <td>
        August 29, 2013
        &nbsp;
      </td>
      <td>James Bradley</td>
    </tr>
    <tr>
      <td>fghgfn</td>
      <td>fghfg</td>
      <td>August 29, 2013</td>
      <td>
        August 29, 2013
        &nbsp;
      </td>
      <td>James Bradley</td>
    </tr>
    <tr>
      <td>August 29, 2013</td>
      <td>fghfg</td>
      <td>August 22, 2013</td>
      <td>
        James Bradley
      </td>
      <td>n/a</td>
    </tr>
    <tr>
      <td>fghfgh</td>
      <td>gfhfh</td>
      <td>August 29, 2013</td>
      <td>
        James Bradley
      </td>
      <td>n/a</td>
    </tr>

  </tbody>
</table>