23

我正在尝试将一个非常大的数据集批量插入到 MySQL 数据库中,并且希望bulk_create在忽略重复错误的同时使用 django。

样品型号:

class MyModel(models.Model):
    my_id=models.IntegerField(primary_key=True)
    start_time = models.DateTimeField()
    duration = models.IntegerField()
    ......
    description = models.CharField(max_length=250)

到目前为止,我有以下代码(对于我的所有模型都是通用的,我传入了 Model_instance() 和 [list of bulk_create objects]):

def insert_many(model, my_objects):
    # list of ids where pk is unique
    in_db_ids = model.__class__.objects.values_list(model.__class__._meta.pk.name)
    if not in_db_ids:
        # nothing exists, save time and bulk_create
        model.__class__.objects.bulk_create(my_objects)
    else:
        in_db_ids_list = [elem[0] for elem in in_db_ids]

        to_insert=[]
        for elem in my_objects:
            if not elem.pk in in_db_ids_list:
                to_insert.append(elem)
        if to_insert:
            model.__class__.objects.bulk_create(to_insert)

有没有办法在 django 中这样做以避免重复?模仿 MySQLinsert ignore会很棒。如果我只是使用bulk_create(非常快),如果主键重复并且插入停止,我会收到错误消息。

4

2 回答 2

16

ignore_conflicts参数添加到bulk_create ( Django 2.2 )

你也可以在https://github.com/django/django/search?q=ignore_conflicts&unscoped_q=ignore_conflicts找到它

于 2019-01-23T10:22:10.170 回答
6

这个功能会做到的。
注意:这只有在你有 uniquepk并且没有其他任何东西时才有效unique

def insert_many(model, my_objects):
    # list of ids where pk is unique
    in_db_ids = model.__class__.objects.values_list(model.__class__._meta.pk.name)
    if not in_db_ids:
        # nothing exists, save time and bulk_create
        model.__class__.objects.bulk_create(my_objects)
    else:
        in_db_ids_list = [elem[0] for elem in in_db_ids]

        to_insert = []
        for elem in my_objects:
            if elem.pk not in in_db_ids_list and elem.pk not in to_insert:
                to_insert.append(elem)
        if to_insert:
            model.__class__.objects.bulk_create(to_insert)

如何使用 insert_many(MyModel(), list_of_myModels_defined_but_not_saved)

于 2013-09-01T09:30:07.743 回答