1

I currently have a django management command to import CSV files, which is based on this answer. The main business is done by the following line in a loop:

created = Customer.objects.get_or_create(account_no = int(row[0]), name = row[1])

However, because I have a number of different models to run this on, I wish to put the above code inside a function, and pass the attributes and row keys in from a dictionary; so I'd defnine something like:

csv_columns = { 0: 'account_no', 1: 'name' }

However I don't know how to run the get_or_create function based on this. I'm sure this should be simple.

v25
  • 7,096
  • 2
  • 20
  • 36

1 Answers1

1

First of all, your dictionaries should look like this:

csv_row = {"account_no": "123-456", "name": "v25"}

Make sure you use a DictReader so that you're reading the csv file's header and then iterating the rows of the csv file correctly, i.e. the keys of each dict yielded are the column names.

Then, the get_or_create call will be a simple unpacking, something like this:

Customer.objects.get_or_create(**csv_row)
wim
  • 338,267
  • 99
  • 616
  • 750
  • Thanks, I couldn't get this method to work, but with help from your link to DictReader, was able to implement this whereby I can specify the django field names IN the CSV which is sufficient for my needs. – v25 Sep 10 '18 at 16:14