CSV导入跳过重复记录
我正在使用django-adaptors我需要一种方法来检查重复的手机号码,并跳过只导入这些记录,同时继续添加其余的CSV文件。CSV导入跳过重复记录
这是我目前CsvModel.py
class ContactCSVModel(CsvModel):
first_name = CharField()
last_name = CharField()
company = CharField()
mobile = CharField()
# groups = DjangoModelField(Groups)
class Meta:
delimiter = "^"
dbModel = Contacts
这是进口
# Try to import CSV
ContactCSVModel.import_from_file(self.filepath)
我不知道如何使用的东西,这个简单的第三方应用程序。只写一个管理命令(其命名为MYAPP /管理/命令/ 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'])
运行,这是真正的一件容易的事:
其中csvimport是你的管理命令的文件名。
我没有看到你的代码检查重复记录的位置? – jason 2013-03-15 18:27:51
'Contacts.objects.get_or_create'从数据库匹配移动设备获取记录,或者使用默认字典创建新记录https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-创建 – 2013-03-15 18:46:16
你所寻找的是更新的Meta选项借此例如...
class Meta:
delimiter = ','
dbModel = Product
update = {
'keys': ['name'] # or mfr_code, main_photo_url, etc..., price
}
会做的伎俩。
请显示您试图执行此操作并且无法正常工作的代码。 – jknupp 2013-03-15 18:07:47