【问题标题】:Django - Url to dynamic model loadingDjango - 动态模型加载的 URL
【发布时间】:2015-07-17 11:01:56
【问题描述】:

所以我正在尝试动态加载模型:

urls.py

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

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

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'

关于安全性,稍后我将只允许来自白名单的课程。

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

【问题讨论】:

标签: python django


【解决方案1】:

如果你想让你的模型动态加载,你可以这样做:

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

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

More information 关于property。基本上,它将将此方法理解为类的属性。不必在类级别定义此属性(意味着在 django 导入文件时将评估代码),您使它看起来像一个属性,但它的作用就像一个方法,允许您添加业务逻辑。

【讨论】:

    【解决方案2】:

    你可以尝试使用property装饰器和get_model方法:

    from django.views.generic import ListView
    from django.apps import apps
    
    
    class GenericList(ListView):
    
        @property
        def model(self):
            # Obtain model name here and pass it to `get_model` below.
            return apps.get_model(app_label='app_label', model_name='model_name')
    

    另外,请考虑阅读 PEP 0008 以了解命名约定。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-15
      • 2023-03-27
      • 2010-11-16
      • 1970-01-01
      • 2013-08-04
      • 2014-09-15
      • 2012-07-10
      • 2020-04-11
      相关资源
      最近更新 更多