在Django

时间:2016-04-22 10:34:41

标签: python django django-models

考虑两个简单的相关模型:

class A(models.Model):
    id = models.IntegerField(primary_key=True)

class B(models.Model):
    a = models.ForeignKey(A)
    # other fields

B上进行非常大量的批量插入之前:

lots_of_b_objects = [B(a_id=1234), B(a_id=5678), ...] 
B.objects.bulk_create(lots_of_b_objects)

(请注意,出于性能原因,我从未在批量创建中实际持有A个对象,我只引用其众所周知的ID,无论它是否存在)

确保所有相关的A对象也存在的高效方法是什么?

现在,我所拥有的最佳解决方案是预先确定相关A的集合并为每个get_or_create()运行A。这不够快。在进行批量插入之前,有没有更好的方法来创建所有a <- data.frame(ID=c("A","B","Z","H"), a=c(0,1,2,45), b=c(3,4,5,22), c=c(6,7,8,3)) b <- data.frame(ID=c("A","B","E","W","Z","H"), a=c(9,10,11,39,5,0), b=c(4,2,7,54,12,34), c=c(12,0,34,23,13,14)) match_a <- na.omit(match(b$ID, a$ID)) match_b <- na.omit(match(a$ID, b$ID)) df <- cbind(ID = a$ID[match_a], a[match_a, -1] + b[match_b, -1]) 个对象?

这里不能对模型进行去标准化,因为数据模型稍微复杂一些。

1 个答案:

答案 0 :(得分:2)

这是一种hackish方式,但这样的事情应该比在循环中使用get_or_create要好得多(但它可能因情况而异,所以我不知道这种方式对你有效)

existing_As = A.objects.filter(id__in=a_ids).values_list('id', flat=True)
As_to_create = list(set(a_ids) - set(existing_As))
A.objects.bulk_create([A(id=x) for x in As_to_create])

# Now we are sure all the As exist as we just created them, so
lots_of_b_objects = [B(a_id=1234), B(a_id=5678), ...] 
B.objects.bulk_create(lots_of_b_objects)