0

私はdjango-adaptors を使用しています.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)
4

2 に答える 2

3

あなたが探しているのは、メタオプションの更新です。この例を見てください...

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

トリックを行います。

于 2013-03-15T20:31:15.057 に答える
1

このような単純なことにサードパーティのアプリを使用することについては知りません。管理コマンドを書くだけです (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 は管理コマンドのファイル名です。

于 2013-03-15T18:19:20.953 に答える