【问题标题】:Django Send_Mail Value ErrorDjango Send_Mail 值错误
【发布时间】:2012-03-14 07:48:03
【问题描述】:

我正在努力使用 QuerySet 作为 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)

我想通过电子邮件发送特定组的邮件列表。我可以通过

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

但是,当我将 mailList 放入我的 send_mail 函数时,我得到一个

Value Error: need more than 1 value to unpack

当我查看 mailList 变量时,它看起来像

[{email: u'someonesname@domain.com'}, {email: u'anothername@domain.com'}]

有什么想法吗?谢谢

PS。我已经看过this stackoverflow question,但它对我没有帮助

想通了

在搞了四个小时的代码后,我终于搞定了。

mailing_list = []

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

【问题讨论】:

  • 这可能一步到位,但未经测试:mailing_list = Customer.objects.filter(group__name='group_two').values_list('email', flat=True)

标签: django email model django-queryset


【解决方案1】:
[{email: u'someonesname@domain.com'}, {email: u'anothername@domain.com'}]

看起来你检查了这个列表:

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

带有值列表:

list(Customer.objects.filter(group__name='group_two').values_list('email'))
...
[(u'someonesname@domain.com',), (u'anothername@domain.com',)]

对于带有 flat=True 的 values_list:

list(Customer.objects.filter(group__name='group_two').values_list('email', flat=True))
...
[u'someonesname@domain.com', u'anothername@domain.com']

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

【讨论】:

    【解决方案2】:

    可能有更好的方法,但你可以试试这个:

    list = []
    for customer in Customer.objects.filter(group__name='group_two').values_list('email'):
        list.append(customer.email)
    
    send_mail('<Subject>', '<Message>', 'from@example.com', list, fail_silently=False)
    

    【讨论】:

    • 谢谢,但这给了我一个“'list' object is not callable”错误
    • 啊,错误发生在尝试使用Customer.objects... 调用list() 时,将该部分保留为已编辑,它应该可以工作,但我看到你已经想通了。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 2011-02-09
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多