Title: Django objects.get_or_create(): passing arguments from dictionary or list
Tags: python;django
Question: 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.


Here is another answer: 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)
Comment for this answer: 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.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2018:00:09/05/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<python><django>', 'Title': 'Django objects.get_or_create(): passing arguments from dictionary or list', 'ViewCount': 809, 'id': 52194186, 'user_AboutMe': None, 'user_AccountId': 2128610.0, 'user_DisplayName': 'v25', 'user_Reputation': 6478.0, 'user_Views': 500.0, 'user_id': 2052575.0}}