Guest User

shawnmilochikcom

a guest
Oct 1st, 2009
557
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.88 KB | None | 0 0
  1. #!/usr/local/bin/python
  2.  
  3. """
  4. Load data from a CSV file into Django.
  5.  
  6. Note: This is a bare-bones example, for the sake
  7. of clarity.
  8. """
  9.  
  10.  
  11. import csv
  12.  
  13. os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
  14.  
  15. from myproject.myapp.models import Item
  16.  
  17. #iterate through the items in the CSV file,
  18. #updating or inserting as necessary
  19.  
  20. INPUT_FILE = '/tmp/some_data.csv'
  21.  
  22. input = csv.DictReader(open(INPUT_FILE))
  23.  
  24. for line in input:
  25.  
  26.     id = int(line['Internal ID'])
  27.  
  28.     #don't duplicate a product, or raise
  29.     #an integrity error e.g., add a new product
  30.     #or update it if it already exists
  31.     current, just_created = Item.objects.get_or_create(internal_id = id)
  32.  
  33.     current.short_desc = line['Description']
  34.     current.weight = float(line['Weight'])        
  35.        
  36.     try:
  37.         current.save()
  38.     except Exception, ex:
  39.         print ex
  40.         break
Advertisement
Add Comment
Please, Sign In to add comment