I'm trying to use django to send emails to a bunch of people at the same time (although right now, I'm trying to get it to work with only one). I have a class called User that has a field email and a foreign-key to a class called Group. Now, I'm trying to send an email to all users in a specific group. To do that, I have the following code:

addresses = User.objects.filter(group__group='Operations').values_list('email')

This is correctly getting the email addresses (if I print the addresses I get [(u'address@example.com',)]. I then use addresses to create an email:

email = EmailMessage('Test', 
         get_template('test.html').render(Context({'content': 'This is a TEST!'})),
         to = addresses) 

When I was doing this before, manually passing in an email address to the "to" argument, it worked perfectly, however now it gives me the error in the title: "ValueError: need more than 1 value to unpack. The line of code that seems to create the error is email.send().

What does this error mean? Why am I getting it? How should I fix it? Is there a better way to get the email addresses out of all the users with the specified group?

Thanks.

有帮助吗?

解决方案 2

Found a solution. Very simple, actually.

addresses = User.objects.filter(group__group='Operations').values_list('email', flat=True)

其他提示

You want to use flat=True in your values_list query.

From the docs:

This is similar to values() except that instead of returning dictionaries, it returns tuples when iterated over.

If you only pass in a single field, you can also pass in the flat parameter. If True, this will mean the returned results are single values, rather than one-tuples.

https://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list

So rather than a list of addresses, your addresses is an iterator that returns tuples of addresses, which is not what EmailMessage is expecting.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top