我创建了一个脚本,允许我向每个用户发送电子邮件。我正在尝试将保存到每个特定用户的术语列表包含在电子邮件中作为文本输出。我已经设法获得所有对象的标题,但我真的想要在名为“saved_searches”的文本字段中获取条目,并且仅针对该特定用户。
以下是相关模型:
class Terms(models.Model):
user = models.ForeignKey(User)
saved_searches = models.TextField()
这是我正在制作的剧本:
#!/usr/bin/env python
from django.core.management.base import NoArgsCommand, CommandError
from django.contrib.auth.models import User
from app.models import Terms
from django.core.mail import EmailMessage
from django.db import connection
class Command(NoArgsCommand):
help = 'Sends emails'
def handle_noargs(self,**options):
try:
self.send_email_alerts()
except Exception, e:
print e
finally:
connection.close()
def send_email_alerts(self):
for user in User.objects.all():
subject = 'Alerts'
from_email="Support <support@email.com>"
terms = Terms.objects.all()
text = 'Hi %s, here are your alerts: %s.' % (user.username, terms)
self.stdout.write("logging here")
msg = EmailMessage(subject, text, from_email, [user.email])
msg.send()
self.stdout.write("sending complete")
答案 0 :(得分:0)
您没有按当前循环用户过滤条款。
此外,如果您只需要saved_searches
使用values_list方法并使用选项flat = True。
terms = user.terms_set.values_list('saved_searches', flat=True)
或
terms = Terms.object.filter(user=user).values_list('saved_searches', flat=True)
对于propper格式化,您应该在添加到字符串模板之前加入这些术语:
text = 'Hi %s, here are your alerts: %s.' % (user.username, ', '.join(terms))