getattr - 异常值:module' django.db.models'没有属性' model_name''

时间:2017-07-20 15:08:56

标签: python django variables getattr

我在模型名称中使用变量时遇到问题,我想使用此命令:

MyVar.objects.all().delete()

并以同样的方式解决问题:

class MyCsvModel(CsvDbModel):
            class Meta:
                dbModel = MyVar
                delimiter = delimiter_csv

这些行为是在一个类的方法上。 和变量在这里创建了方法。

对不起我的英语,我是初学者......

编辑:

我的代码:

from etl.models import MvmtjExportTemps, MvmtjExport
from django.db import models

[...]
model_name = self.table_temporaire[self.numero_edi]
getattr(models, model_name).objects.all().delete()


class MyCsvModel(CsvDbModel):
    class Meta:
        dbModel = getattr(models, model_name)
        delimiter = delimiter_csv

我有这个结果:

  

环境:

     

请求方法:GET请求URL:   http://127.0.0.1:8000/etl/integration/

     

Django版本:1.8.18 Python版本:3.6.1已安装的应用程序:   [' django.contrib.admin',' django.contrib.auth',   ' django.contrib.contenttypes',' django.contrib.sessions',   ' django.contrib.messages',' django.contrib.staticfiles',' pec',   '拓扑',' bootstrap3_datetime',' todo_app',' debug_toolbar',' bi',   ' etl']已安装的中间件:   [' debug_toolbar.middleware.DebugToolbarMiddleware&#39 ;,   ' django.middleware.security.SecurityMiddleware&#39 ;,   ' django.contrib.sessions.middleware.SessionMiddleware&#39 ;,   ' django.middleware.common.CommonMiddleware&#39 ;,   ' django.middleware.csrf.CsrfViewMiddleware&#39 ;,   ' django.contrib.auth.middleware.AuthenticationMiddleware&#39 ;,   ' django.contrib.auth.middleware.SessionAuthenticationMiddleware&#39 ;,   ' django.contrib.messages.middleware.MessageMiddleware&#39 ;,   ' django.middleware.clickjacking.XFrameOptionsMiddleware']

     

回溯:文件   " C:\ GIT中\ ATH_intranet \ env_p3 \ lib中\站点包\ django的\芯\处理程序\ base.py"   在get_response中     132. response = wrapped_callback(request,* callback_args,** callback_kwargs)File" c:\ git \ ATH_intranet \ etl \ views.py"在IntegrationExtraction中     188. importation.ImportationTableTemporaire(fichier)文件   " C:\ GIT中\ ATH_intranet \ ETL \ class_perso.py"在ImportationTableTemporaire中     112. getattr(models,model_name).objects.all()。delete()

     

异常类型:/ etl / integration / Exception值中的AttributeError:   模块' django.db.models'没有属性' MvmtjExportTemps'

编辑2:

最后我需要在import和getattr中添加位置,如下所示:

import etl.models

        #vidange table temporaire
        model_name = self.table_temporaire[self.numero_edi]
        getattr(etl.models, model_name).objects.all().delete()

        # creation de la class correspondant a la table temporaire

        class MyCsvModel(CsvDbModel):
            class Meta:
                dbModel = getattr(etl.models, model_name)
                delimiter = delimiter_csv

1 个答案:

答案 0 :(得分:0)

import models 
model_name = "X"

getattr(models, model_name).objects.all().delete()

class MyCsvModel(CsvDbModel):
            class Meta:
                dbModel = getattr(models, model_name)
                delimiter = delimiter_csv