我正在使用 bulk_create 将数千或行加载到 postgresql 数据库中。不幸的是,某些行导致了 IntegrityError 并停止了 bulk_create 进程。我想知道是否有办法告诉 django 忽略这些行并尽可能多地保存批处理?
最佳答案
现在可以在 Django 2.2 上实现
Django 2.2 为 bulk_create
方法添加了一个新的 ignore_conflicts
选项,来自 documentation :
On databases that support it (all except PostgreSQL < 9.5 and Oracle), setting the ignore_conflicts parameter to True tells the database to ignore failure to insert any rows that fail constraints such as duplicate unique values. Enabling this parameter disables setting the primary key on each model instance (if the database normally supports it).
例子:
Entry.objects.bulk_create([
Entry(headline='This is a test'),
Entry(headline='This is only a test'),
], ignore_conflicts=True)
关于Django bulk_create 忽略导致 IntegrityError 的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12451053/