2012-02-23 80 views
0

我奮力用一個QuerySet作爲收件人arguement的send_mail功能Django的Send_Mail值錯誤

我有這樣的模式:

class Group(models.Model): 
    name = models.CharField(primary_key=True) 
    mailing_list = models.ManyToManyField("Customer", null=True) 

class Customer(models.Model): 
    name = models.CharField() 
    email = models.EmailField(primary_key=True) 

我想通過電子郵件發送的mailing_list特定組。我可以通過

mailList = list(Customer.objects.filter(group__name='group_two').values_list('email')) 

訪問此然而,當我把郵件列表在我的send_mail功能我得到一個

Value Error: need more than 1 value to unpack 

當我看maillist的變量,它看起來像

[{email: u'[email protected]'}, {email: u'[email protected]'}] 

任何想法?謝謝

PS。我看了this stackoverflow question已經,但它不是真的對我很有幫助

想通了

4小時的代碼我終於得到它亂搞後。

mailing_list = [] 

for contact in Customer.objects.filter(group__name='group_two'): 
    mailing_list.append(contact.email) 
+0

這可以在一個步驟中工作,但它不是進行測試:'mailing_list = Customer.objects.filter(group__name = 'group_two' ).values_list('email',flat = True)' – Furbeenator 2012-02-23 21:45:24

回答

0

有可能是一個更好的辦法,但你可以試試這個:

list = [] 
for customer in Customer.objects.filter(group__name='group_two').values_list('email'): 
    list.append(customer.email) 

send_mail('<Subject>', '<Message>', '[email protected]', list, fail_silently=False) 
+0

謝謝,但這給了我一個''列表'對象不可調用「錯誤 – dannymilsom 2012-02-23 21:34:26

+0

啊,發生錯誤嘗試調用'list()'與Customer.objects ......「把這部分編輯出來,它應該可以工作,但我知道你已經明白了。 :-) – Furbeenator 2012-02-23 21:44:33

0
[{email: u'[email protected]'}, {email: u'[email protected]'}] 

它看起來像你查看該列表:

list(Customer.objects.filter(group__name='group_two').values('email')) 

與values_list:

list(Customer.objects.filter(group__name='group_two').values_list('email')) 
... 
[(u'[email protected]',), (u'[email protected]',)] 

以及用於與values_list平=真:

list(Customer.objects.filter(group__name='group_two').values_list('email', flat=True)) 
... 
[u'[email protected]', u'[email protected]'] 

檢查文檔 https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values_list