我使用以下数据作为测试创建了完整的脚本:
"http://www.graychase.com/aabbas","Gray & Chase LLP","Amr A","Abbas","The George Washington University Law School","2005""http://www.graychase.com/kadam","Gray & Chase LLP","Karin","Adam","Ernst Moritz Arndt University Greifswald","2004"
请注意,上面示例中的CSV文件 是WRONG
。csv文件阅读器将读取整行作为条目,因为整行都用引号引起来。从csv文件的每一行中删除开头和结尾的引号,或者像我一样,将行中的每个不同值都括在引号中。
这是将与以下脚本一起使用的模型:
from django.db import modelsclass School(models.Model): name = models.CharField(max_length=300, unique=True) def __unipre__(self): return self.nameclass Lawyer(models.Model): firm_url = models.URLField('Bio', max_length=200, unique=True) firm_name = models.CharField('Firm', max_length=100) first = models.CharField('First Name', max_length=50) last = models.CharField('Last Name', max_length=50) year_graduated = models.IntegerField('Year graduated') school = models.ForeignKey(School) def __unipre__(self): return self.first这是将读取CSV文件的脚本(除非我弄错了您的项目
sw2和应用程序的名称
wkw2,然后修复这些引用):
############ All you need to modify is below ############# Full path and name to your csv filecsv_filepathname="C:/Users/A/documents/Projects/Django/sw2/wkw2/fixtures/data.csv"# Full path to the directory immediately above your django project directoryyour_djangoproject_home="C:.../documents/PROJECTS/Django/"############ All you need to modify is above ############import sys,ossys.path.append(your_djangoproject_home)os.environ['DJANGO_SETTINGS_MODULE'] ='sw2.settings'from sw2.wkw2.models import School, Lawyerimport csvdataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"')old_school = Nonefor row in dataReader: if old_school != row[4]: old_school = row[4] school = School() school.name = old_school school.save()dataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='"')for row in dataReader: lawyer=Lawyer() lawyer.firm_url=row[0] lawyer.firm_name=row[1] lawyer.first=row[2] lawyer.last=row[3] lawyer_school=School.objects.get(name=row[4]) lawyer.school=lawyer_school lawyer.year_graduated=row[5] lawyer.save()
该脚本首先从CSV文件中的可用学校创建每个可能的学校。然后,它再次通过CSV运行并创建每个律师。
我用测试数据运行了这个脚本。它可以正常工作并加载所有CSV数据。



