我正在尝试将一个非常大的数据集批量插入到 MySQL 数据库中,并且希望在忽略重复错误的同时使用 django 的 bulk_create
。
示例模型:
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 有没有办法这样做以避免重复?模仿 MySQL 的 insert ignore
会很棒。如果我只是使用 bulk_create
(非常快),如果主键重复并且插入停止,我会收到错误消息。
最佳答案
ignore_conflicts 参数已添加到 bulk_create(Django 2.2)
您也可以在 https://github.com/django/django/search?q=ignore_conflicts&unscoped_q=ignore_conflicts 中找到它
关于python - django批量创建忽略重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17311059/