【问题标题】:AttributeError: module ' ' has no attribute 'Command'AttributeError: 模块“”没有属性“命令”
【发布时间】:2021-11-12 05:10:02
【问题描述】:

在我的 Django 项目中,有一个文件(模块)用于加载 csv 数据。

project/apps/patients/management/commands/load_patient_data.py

文件(模块)内部:

import psycopg2
import csv
conn = psycopg2.connect(host='localhost', dbname='patientdb',user='username',password='password',port='')
cur = conn.cursor()

with open(r'apps/patients/management/commands/events.csv') as csvfile:
        spamreader = csv.DictReader(csvfile, delimiter=',' ,quotechar=' ')
        for row in spamreader:
            cur.execute(f"""INSERT INTO patients_event (patient_id, event_type_id , event_value ,event_unit, event_time) VALUES
                  ('{row['PATIENT ID']}','{row['EVENT TYPE']}','{row['EVENT VALUE']}',
                   '{row['EVENT UNIT']}','{row['EVENT TIME']}')""")
conn.commit()

当我跑步时:

 python manage.py load_patient_data

错误:

AttributeError: module 'apps.patients.management.commands.load_patient_data' has no attribute 'Command'

有朋友可以帮忙吗?

【问题讨论】:

  • 看起来你正在运行一个简单的脚本作为 django 命令。你试过运行python project/apps/patients/management/commands/load_patient_data.py吗?如果您想将其作为命令运行,则必须遵循 django docs.djangoproject.com/en/3.2/howto/custom-management-commands 的命令 API
  • 谢谢,它可以自定义命令,请您将其发布为答案,我会检查它。

标签: python django django-models django-rest-framework django-views


【解决方案1】:

load_patient_data.py 文件中

如下写

from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):

    def handle(self, *args, **options):
        import psycopg2
        import csv
        conn = psycopg2.connect(host='localhost', dbname='patientdb', user='username', password='password', port='')
        cur = conn.cursor()
    
        with open(r'apps/patients/management/commands/events.csv') as csvfile:
            spamreader = csv.DictReader(csvfile, delimiter=',', quotechar=' ')
            for row in spamreader:
                cur.execute(f"""INSERT INTO patients_event (patient_id, event_type_id , event_value ,event_unit, event_time) VALUES
                          ('{row['PATIENT ID']}','{row['EVENT TYPE']}','{row['EVENT VALUE']}',
                           '{row['EVENT UNIT']}','{row['EVENT TIME']}')""")
        conn.commit()

然后只需运行 python manage.py load_patient_data

【讨论】:

    猜你喜欢
    • 2018-04-14
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 2019-07-20
    • 2021-11-05
    • 2021-11-04
    相关资源
    最近更新 更多