我不知道将 3rd 方应用程序用于这么简单的事情。只需编写一个管理命令(将其命名为 myapp/management/commands/csvimport.py):
from django.core.management.base import BaseCommand, CommandError
from fabric.colors import _wrap_with
from optparse import make_option
import os, csv
green_bg = _wrap_with('42')
red_bg = _wrap_with('41')
class Command(BaseCommand):
help = "Command to import a list of stuff"
option_list = BaseCommand.option_list + (
make_option(
"-f",
"--file",
dest = "filename",
help = "specify import file",
metavar = "FILE"
),
)
def handle(self, *args, **options):
# make sure file option is present
if options['filename'] == None :
raise CommandError("Option `--file=...` must be specified.")
# make sure file path resolves
if not os.path.isfile(options['filename']) :
raise CommandError("File does not exist at the specified path.")
# print file
print green_bg("Path: `%s`" % options['filename'])
# open the file
with open(options['filename']) as csv_file:
reader = csv.reader(csv_file)
for row in reader:
try :
object, created = Contacts.objects.get_or_create(
mobile = row[3],
defaults={
"first_name": row[0],
"last_name": row[1],
"company": row[2],
}
)
except:
print red_bg("Contacts `%s` could not be created." % row['mobile'])
运行它也很容易:
python manage.py csvimport --file=path/to/myfile.csv
其中 csvimport 是管理命令的文件名。