Skip to content

Instantly share code, notes, and snippets.

@diek
Created November 27, 2020 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diek/a54bfe282fc02638290a694ede7b61f9 to your computer and use it in GitHub Desktop.
Save diek/a54bfe282fc02638290a694ede7b61f9 to your computer and use it in GitHub Desktop.
Django Management Command - Upload data from csv
import csv
from django.core.management.base import BaseCommand
from expenditures.models import Salary
class Command(BaseCommand):
help = "Insert N Rows of Salaries"
@property
def get_data(self):
salaries = []
with open("city_salaries.csv", newline="") as csvfile:
reader = csv.DictReader(csvfile)
next(reader)
for row in reader:
salaries.append(
[
row["Name"],
row["Job_Titles"],
row["Department"],
row["Annual_Salary"],
]
)
return salaries
def handle(self, *args, **options):
employees = self.get_data
if employees:
for emp in employees:
employee = Salary(
name=emp[0],
position_title=emp[1],
department=emp[2],
salary=emp[3],
)
employee.save()
else:
print("empty list")
print("Job complete")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment