我正在使用Django 1.9,并且正在尝试使用bulk_create创建许多新模型对象,并将它们与公共相关的many_to_many对象相关联。Django在执行bulk_create时设置many_to_many对象
我的型号如下
#Computational Job object
class OT_job(models.Model):
is_complete = models.BooleanField()
is_submitted = models.BooleanField()
user_email = models.EmailField()
#Many sequences
class Seq(models.Model):
sequence=models.CharField(max_length=100)
ot_job = models.ManyToManyField(OT_job)
我有数以千计的被提交,并且必须与它们相关的作业相关的序列对象。以前我使用迭代器并将它们保存在for循环中。但在阅读后意识到Django 1.9有bulk_create。
目前我做
DNASeqs_list = []
for a_seq in some_iterable_with_my_data:
# I create new model instances and add them to the list
DNASeqs_list.append(Seq(sequence=...,))
我现在想bulk_create这些序列,并将其与current_job_object关联。
created_dnaseqs = Seq.objects.bulk_create(DNASeqs_list)
# How do I streamline this part below
for a_seq in created_dnaseqs:
# Had to call save here otherwise got an error
a_seq.save()
a_seq.ot_job.add(curr_job_obj)
我不得不打电话给“a_seq.save()”中的循环,因为我在我做“a_seq.ot_job.add(curr_job_obj)”,这说
部分错误。 ...在使用这种多对多关系之前,需要有一个字段“seq”的值。
尽管阅读other questions on this topic,我仍然感到困惑,因为不像其他人,我没有一个自定义的“通过”模型。我很困惑如何最好地将OT_Job与许多Seq关联起来,并将最小命中数据库与数据库关联起来。
感谢您的澄清。我错过了文档中的那一点。现在我也知道为什么一些BulkOverflow上的bulk_create示例在bulk_create后立即执行检索。 – harijay