2012-12-30 39 views
2

我發出的信息,我需要跟蹤每封郵件被髮送出去的時候,給誰等創建像INSERT許多相關的對象...選擇在SQL

所以我有收件人在除了消息之外的額外表模型中,並且每次創建新消息時都需要填充收件人。消息的Recipient將從第三個模型填充,該模型包含我想要發送到的所有當前電子郵件地址。

所以我的問題是我將如何去這個最有效的方式?
我知道我可以做類似的東西:

m = Message.objects.create(*args) 
for email in ModelWithEmails.active.values_list('email', flat=True): 
    Recipient.objects.create(message=m, email=email) 

但是,這仍然會涉及到讓所有的電子郵件地址從數據庫中,我想如果可能的話,以保持它的所有數據庫裏面的,如有幾千個地址每次都會被提取。

回答

3

你不能這樣做INSERT。與Django的ORM選擇,但你可以做批量插入(因爲Django的1.4):

m = Message.objects.create(*args) 
recipients = [] 
for email in ModelWithEmails.active.values_list('email', flat=True): 
    recipients.append(Recipient(message=m, email=email)) 

Recipient.objects.bulk_create(recipients) 

  或者一點點更高效:

m = Message.objects.create(*args) 
emails = ModelWithEmails.active.values_list('email', flat=True) 
Recipient.objects.bulk_create([Recipient(message=m, email=email) for email in emails]) 

 

對於INSERT .. SELECT,您必須回退到原始SQL。

+0

謝謝,不是我想要的,但這是使用抽象層的幾個缺點之一。 :) – gaqzi

1

Django ORM不再需要用戶使用原始sql。這是非常方便的,但它可能不是很靈活。 如果你想使用ORM,bulk_create將成爲你的朋友,就像Pavel Anossov說的那樣。