Created
November 27, 2020 17:42
-
-
Save diek/a54bfe282fc02638290a694ede7b61f9 to your computer and use it in GitHub Desktop.
Django Management Command - Upload data from csv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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