<p>关于已接受答案的一个注释:它将给出所需的结果,但会使磁盘的使用率和时间与大文件一起急剧下降。在</p>
<p>我一直使用的一种更有效的方法(在花了大量时间浏览文档之后)是重写<code>skip_row</code>,并将一组元组作为类的一部分作为唯一约束。我仍然覆盖<code>save_instance</code>,因为另一个答案建议处理通过的integrityerror。在</p>
<p>Python<code>sets</code>不创建重复的条目,因此它们似乎适合这种唯一索引。在</p>
<pre><code>class CompositionsResource(resources.ModelResource):
set_unique = set()
class Meta:
model = Composers
skip_unchanged = True
report_skipped = True
def before_import(self, dataset, using_transactions, dry_run, **kwargs):
# Clear out anything that may be there from a dry_run,
# such as the admin mixin preview
self.set_unique = set()
def skip_row(self, instance, original):
composer_key = instance.composer_key # Could also use composer_key_id
composition = instance.composition
tuple_unique = (composer_key, composition)
if tuple_unique in self.set_unique:
return true
else:
self.set_unique.add(tuple_unique)
return super(CompositionsResource, self).skip_row(instance, original)
# save_instance override should still go here to pass on IntegrityError
</code></pre>
<p>这种方法至少可以减少在同一个数据集中遇到的重复。我用它来处理多个平面文件,每个文件大约60000行,但是有很多重复的/嵌套的外键。这使得初始数据导入速度更快。在</p>