2012-02-23 60 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