我正在尝试批量插入一个非常大的数据集的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)
Run Code Online (Sandbox Code Playgroud)
到目前为止,我有以下代码(所有模型的通用,我传入Model_instance()和[bulk_create对象列表]):
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)
Run Code Online (Sandbox Code Playgroud)
django有没有办法做到这一点,以避免重复?模仿MySQL insert ignore
会很棒.如果我只是使用bulk_create
(非常快),如果主键重复并且插入停止,我会收到错误.
只是想知道是否有一个免费的parse.com
替代方案,允许人们在表中任意存储数据并动态创建数据库(例如在mysql中),就像parse.com一样.
我很想知道并使用它,然后花时间创建一个.
谢谢!
我正在努力有效地改变:
[{'text': 'hallo world', 'num': 1},
{'text': 'hallo world', 'num': 2},
{'text': 'hallo world', 'num': 1},
{'text': 'haltlo world', 'num': 1},
{'text': 'hallo world', 'num': 1},
{'text': 'hallo world', 'num': 1},
{'text': 'hallo world', 'num': 1}]
Run Code Online (Sandbox Code Playgroud)
到没有重复的字典列表和重复的计数:
[{'text': 'hallo world', 'num': 2, 'count':1},
{'text': 'hallo world', 'num': 1, 'count':5},
{'text': 'haltlo world', 'num': 1, 'count':1}]
Run Code Online (Sandbox Code Playgroud)
到目前为止,我有以下内容来查找重复项:
result = [dict(tupleized) for tupleized in set(tuple(item.items()) for item in li)]
Run Code Online (Sandbox Code Playgroud)
它返回:
[{'text': 'hallo world', 'num': 2},
{'text': 'hallo world', 'num': 1},
{'text': 'haltlo …
Run Code Online (Sandbox Code Playgroud)