Python 将字符串转化为Class(对象)

1.通过getattr()方法获取

import importlib

model_name ='StationSite'
model_path = 'doctor.models'
params = importlib.import_module(model_path)
model = getattr(params, model_name)
res= model.objects.fliter().all()

2.直接使用globals()方法

import importlib

from doctor.models import StationSite
model=globals().get('StationSite')
if not model:
    model = importlib.import_module("doctor.models").__dict__.get('StationSite')
res= model.objects.fliter().all()

你可能感兴趣的:(Python 将字符串转化为Class(对象))