I am trying to setup a website in django which allows the user to send queries to a database containing information about their representatives in the European Parliament. I have the data in a comma seperated .txt file with the following format:
Parliament, Name, Country, Party_Group, National_Party, Position
7, Marta Andreasen, United Kingdom, Europe of freedom and democracy Group, United Kingdom Independence Party, Member
etc….
I want to populate a SQLite3 database with this data, but so far all the tutorials I have found only show how to do this by hand. Since I have 736 observations in the file I dont really want to do this.
I suspect this is a simple matter, but I would be very grateful if someone could show me how to do this.
Thomas
So assuming your
models.pylooks something like this:You can then run
python manage.py shelland execute the following:And you’re done.
Addendum (edit)
Per Thomas’s request, here’s an explanation of what
**dict(zip(fields,row))does:So initially,
fieldscontains a list of field names that we defined, androwcontains a list of values that represents the current row in the CSV file.What
zip()does is it combines two lists into one list of pairs of items from both lists (like a zipper); i.e.zip(['a','b,'c'], ['A','B','C'])will return[('a','A'), ('b','B'), ('c','C')]. So in our case:The
dict()function simply converts the list of pairs into a dictionary.The
**is a way of converting a dictionary into a keyword argument list for a function. Sofunction(**{'key': 'value'})is the equivalent offunction(key='value'). So in out example, callingcreate(**dict(zip(field, row)))is the equivalent of:Hope this clears things up.