下面是我的直通表:
class ThroughTable(models.Model):
user = models.ForeignKey(User)
society = models.ForeignKey(Society)
我得到了2个列表,其中包含2个模型对象的in,它们必须添加到我的直通表中。
user_list = [1,2,5,6,9]
society_list = [1,2,3,4]
在这里,我想在直通表中为这两个列表中的每个可能的对创建条目。
我正在考虑使用嵌套循环来迭代和创建直通表中的对象,但它看起来非常幼稚,并且复杂度为n*n。
有没有更好的方法来解决这个问题?
发布于 2020-06-26 22:38:13
Django提供了一个bulk_create()方法来在数据库中创建条目。它有可选的参数batch_size,因为如果你有数百万条记录,你不能一次输入所有的记录,所以分批打破记录并进入数据库。
ThroughTable.objects.bulk_create(item, batch_size)
发布于 2020-06-27 00:52:07
来自the docs
bulk_create(objs,batch_size=None,ignore_conflicts=False)
这个方法以一种高效的方式将提供的对象列表插入到数据库中>(通常只有一个查询,不管有多少个对象):
对于您的案例,首先创建一个包含所有可能组合的列表,然后保存它。
items = []
for user, society in user_list:
for society in society_list:
item = ThroughTable(user=user, society=society)
items.append(item)
ThroughTable.objects.bulk_create(items)
https://stackoverflow.com/questions/62596395
复制相似问题