谢谢guys.i设法完成了它。万岁再次特别感谢DAVID,WM-EDDIE和S.LOTT.also STACKOVERFLOW
解决方案:
**model = Contact()
model.contact_owner = request.user
model.contact_name = row[1]
model.contact_mobile_no = row[2]
model.select_group = row[3]
model.save()**
我的user.py
def import_contact(request):
if request.method == 'POST':
form = UploadContactForm(request.POST, request.FILES)
if form.is_valid():
csvfile = request.FILES['file']
print csvfile
csvfile.read()
testReader = csv.reader(csvfile,delimiter=' ', quotechar='|')
**#what code should i write here to store data in mysql**
for row in testReader:
print "|".join(row)
return HttpResponseRedirect('/admin')
else:
form = UploadContactForm()
vars = RequestContext(request, { 'form': form })
return render_to_response('admin/import_contact.html', vars)
csv文件中的数据:
阿布巴卡尔,鲁尼,0178222123,学生
阿布巴卡尔,罗,0183886789,学生
阿布巴卡尔,卡卡,0197887898,博拉
感谢任何建议。希望能给我看一些编码示例因为我仍然是这种语言的初学者
my models.py:
class Contact(models.Model):
contact_owner = models.ForeignKey(User, related_name="contacts")
contact_name = models.CharField(max_length=20)
contact_mobile_no = models.CharField(max_length=20)
select_group = models.CharField(max_length=20, null=True)
def __unicode__(self):
return "contact {contact_owner=%s, contact_name=%s, contact_mobile_no=%s, select_group=%s}" % (self.contact_owner, self.contact_name, self.contact_mobile_no, self.select_group)
答案 0 :(得分:0)
标记逗号分隔的字符串:
>>> a = 'abubakar,rooney,0178222123,student abubakar,rooneyzzz,0178222164'
>>> b = a.split(',')
>>> print b
['abubakar', 'rooney', '0178222123', 'student abubakar', 'rooneyzzz', '0178222164']
请参阅@ wm_eddie的答案,了解如何在数据库中创建新条目。
答案 1 :(得分:0)
Python的手册非常糟糕。您应该“推测”因为它们使用string.join(),该行就像列表一样工作。所以它几乎将CSV文件解析为列表列表。它会处理所有令人讨厌的引用,并为你逃避。
您使用它就像使用数组/列表一样
for row in testReader:
model = YourModel()
model.property_a = row[0]
model.property_b = row[1]
model.save()
还有一个DictReader,它允许你写一个更可读的:
for row in testReader:
model = YourModel()
model.property_a = row["prop_a"]
model.property_b = row["prop_b"]
model.save()
答案 2 :(得分:0)
这与我们的工作大致相同。
header = 'contact_owner', 'contact_name', 'contact_mobile_number', 'select_group'
rdr= csv.reader(request.FILES['file'])
for row in rdr:
data = zip( header, row )
owner, created = User.get_or_create( data['contact_owner']
data['contact_owner']= owner
contact, created = Contact.get_or_create( **data )
logger.info( "Created %r", contact )
http://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create-kwargs
您的问题是“逗号分隔符”。您的示例数据使用逗号。但是您的csv.reader
代码会显示空格。这是什么?
答案 3 :(得分:0)
with open(path) as f:
reader = csv.reader(f)
for row in reader:
_, created = Student.objects.get_or_create(
first_name=row[0],
last_name=row[1],
middle_name=row[2],
)
# creates a tuple of the new object or
# current object and a boolean of if it was created
在我的示例中,model student有三个属性first_name,last_name和middle_name。