Added basic importing command from CSV.

This commit is contained in:
2013-04-03 22:12:34 +01:00
parent 131b2e46ef
commit 88666e5949
4 changed files with 48 additions and 1 deletions

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,46 @@
import csv
import requests
from StringIO import StringIO
from django.db import transaction
from django.core.management.base import BaseCommand, CommandError
from stores.models import Country, County, Address, Store
class Command(BaseCommand):
args = '<file or url>'
help = 'Import a list of stores from CSV'
def handle(self, *args, **options):
file = args[0]
if file.startswith('http'):
self.stdout.write("Downloading %s\n" % file)
f = StringIO(requests.get(file).text)
else:
self.stdout.write("Opening file %s\n" % file)
f = open(file, 'r')
for row in csv.reader(f):
row = [x.strip() for x in row]
name, addr1, addr2, addr3, city, county, country, postcode, email, website, phone, y, x, twitter, facebook, facebook2 = row
self.stdout.write("Importing %s... " % name)
try:
obj = Store.objects.get(name=name)
except Store.DoesNotExist:
pass
else:
if obj.address.postcode == postcode:
self.stdout.write("Store by that name already exists, skipping.\n")
continue
with transaction.commit_on_success():
country, created = Country.objects.get_or_create(name=country)
county, created = County.objects.get_or_create(name=county, country=country)
addr = Address(name=name, address1=addr1, address2=addr2, address3=addr3, city=city, county=county, country=country, postcode=postcode, geo_latitude=y, geo_longitude=x)
addr.save()
store = Store(name=name, address=addr, website=website, email=email, phone=phone)
if website:
store.store_type = Store.STORE_TYPE_BOTH
store.save()
self.stdout.write("Done\n")
f.close()
self.stdout.write("Done\n")

View File

@@ -50,7 +50,7 @@ class Store(models.Model):
name = models.CharField('Name', max_length=200, help_text="Store's full name")
slug = models.SlugField('URL Slug', max_length=200, blank=True)
address = models.ForeignKey('stores.Address', related_name='stores')
store_type = models.IntegerField('Store Type', choices=STORE_TYPE_CHOICES)
store_type = models.IntegerField('Store Type', choices=STORE_TYPE_CHOICES, default=STORE_TYPE_RETAIL)
chain = models.ForeignKey(Chain, related_name='stores', null=True, blank=True)
editor = models.ForeignKey(USER_MODEL, related_name='editable_stores', null=True, blank=True)
active = models.BooleanField('Active?', default=True)