2013-03-15 125 views
0

我正在使用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) 
+3

請顯示您試圖執行此操作並且無法正常工作的代碼。 – jknupp 2013-03-15 18:07:47

回答

1

我不知道如何使用的東西,這個簡單的第三方應用程序。只寫一個管理命令(其命名爲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是你的管理命令的文件名。

+0

我沒有看到你的代碼檢查重複記錄的位置? – jason 2013-03-15 18:27:51

+0

'Contacts.objects.get_or_create'從數據庫匹配移動設備獲取記錄,或者使用默認字典創建新記錄https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-創建 – 2013-03-15 18:46:16

3

你所尋找的是更新的Meta選項藉此例如...

class Meta: 
     delimiter = ',' 
     dbModel = Product 
     update = { 
      'keys': ['name'] # or mfr_code, main_photo_url, etc..., price 
     } 

會做的伎倆。