在 CBV 中动态检索模型 class

Retrieving model class dynamically in CBV

在 CBV 中动态检索模型 class 的正确方法是什么?

我知道我必须使用 apps.get_model,但不确定在哪里使用。

我想让我的删除(和其他)视图更多"DRY"。

class DeleteParamView(generic.DeleteView):
    # The following does not work since kwargs cannot be accessed
    #model = apps.get_model('patients', 'param' + self.kwargs['param_name'])  

    def __init__(self, *args, **kwargs):
        from django.apps import apps
        self.model = apps.get_model('persons', 'param' + self.kwargs['param_name'])
        super(DeleteParamView, self).__init__(*args, **kwargs)

很遗憾self.kwargs还不能访问;至少我得到 'DeleteParamView' object has no attribute 'kwargs'

我也尝试覆盖 def get_model(),但它不作为 CBV 的一部分存在。

覆盖 get_queryset 方法。

def get_queryset(self):
    Model = apps.get_model('persons', 'param' + self.kwargs['param_name'])
    return Model.objects.all()