2017-02-13 96 views
0

我正在使用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關聯起來,並將最小命中數據庫與數據庫關聯起來。

回答

1

從文檔https://docs.djangoproject.com/en/1.9/ref/models/querysets/#bulk-create

如果模型的主鍵是一個下拉列表AutoField它不檢索和設置主鍵屬性,如保存()一樣。

它不適用於多對多的關係。

bulk_create硬是將剛剛創建的對象,它並沒有檢索到PK的變量save一樣。您將不得不重新查詢數據庫以獲取新創建的對象,然後創建M2M關係,但聽起來這樣做不合適,而且您當前的方法目前是最佳解決方案。

+0

感謝您的澄清。我錯過了文檔中的那一點。現在我也知道爲什麼一些BulkOverflow上的bulk_create示例在bulk_create後立即執行檢索。 – harijay