Django-动态模型加载的网址 [英] Django - Url to dynamic model loading

查看:40
本文介绍了Django-动态模型加载的网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图像这样动态加载模型:

So I'm trying to load a model dynamically as such :

urls.py

url(r'^list_view/([\w-]+)$', Generic_list.as_view()),

这是我在 views.py 中的Generic_list类:

Here's my Generic_list class in views.py :

class Generic_list(ListView):
    import importlib
    module_name = 'models'
    class_name = ?
    module = __import__(module_name, globals(), locals(), class_name)
    model = getattr(module, class_name)
    template_name = 'django_test/generic_list.html'

关于安全性,稍后我将只允许白名单中的类.

About security, later I'll only allow classes from a white list.

那么,为了从url获得类名,我可以用什么代替问号呢?

So, what can I put in place of the question mark in order to get the class name from the url?

推荐答案

如果要动态加载模型,可以执行以下操作:

If you want to have your model loaded dynamically, you could do something like this:

class Generic_list(ListView):
    template_name = 'django_test/generic_list.html'

    @property
    def model(self):
        return # code that returns the actual model

有关属性的更多信息.基本上,它将将此方法理解为类的属性.不必在类级别定义此属性(这意味着在django导入文件时将对代码进行评估),而使它看起来像是一个属性,但是它就像一种方法,允许您添加业务逻辑.

More information about property. Basically, it will understand this method as an attribute of the class. Instead of having to define this attribute at the class level (meaning that the code will be evaluated when the file is imported by django), you make it look like it is an attribute, but it's acting like a method, allowing you to add business logic.

这篇关于Django-动态模型加载的网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆