如何动态加载Django类

时间:2015-09-04 21:00:10

标签: python django class load

从数据库我有一个文本,它必须动态加载我的一类视图。

我现在的例子是:

-projectname
    -appname
        -views.py
        -templates
            -appname
                -index.html
在views.py中

class SelectCampaign(View):

    def get(self, request, *args, **kwargs):

        campaign = Campaign.objects.values('campaign_name').filter(user=request.user)[0]

        #this is where I need you to automatically load with varying campaign
        generic_class = MyClassCampaignName1() 
        #example: generic_class = class called MyClassCampaignName1

        return generic_class.render_index(request)

class MyClassCampaignName1():

    def render_index(self, request, *args, **kwargs):
        return render(request, 'appname/index.html', {}, context_instance=RequestContext(request))

使数据库动态加载具有相同名称的类的名称

1 个答案:

答案 0 :(得分:0)

以下是从字符串名称中获取对象的几种方法。我最喜欢getattr

# outside.py
class OuterDummy():
    def __init__(self):
        print 'This is outer Dummy!'

# main.py
class InnerDummy():
    def __init__(self):
        print 'This is inner Dummy!'

if __name__ == "__main__":
    # Method 1) Use the globals object
    class_1 = globals().get('InnerDummy')
    instance_1 = class_1()
    # stdout: This is inner Dummy!

    # Method 2) Use getattr
    import outside
    class_2 = getattr(outside, 'OuterDummy')
    instance_2 = class_2()
    # stdout: This is outer Dummy!

python main.py