In my Django project ,there is a file(module) which is used to load csv data.
project/apps/patients/management/commands/load_patient_data.py
Inside the file(module):
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()
When I run:
python manage.py load_patient_data
Error:
AttributeError: module 'apps.patients.management.commands.load_patient_data' has no attribute 'Command'
Any friend can help?
CodePudding user response:
In load_patient_data.py
file
Write follwing
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()
Then simply run python manage.py load_patient_data