在对象满足特定条件后发送电子邮件

时间:2012-09-11 19:11:28

标签: python django django-email

[希望我能正确地发布这篇文章]

我有一个(有点)'跟随'推特的事情。用户可以关注company个人资料对象,该对象会创建follower个对象。

class Follower(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    profile = models.ForeignKey(UserProfile)
    company = models.ForeignKey(Company)
    verified = models.BooleanField(default=False)
    from_user = models.BooleanField(default=False)

...

class Company(models.Model):
    owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL)
    name = models.CharField(max_length=200)
    ... and more fields that aren't relevant

我想做的是在5位新关注者之后向公司资料所有者发送更新电子邮件。 “你有5个新粉丝!”。

截至目前,我每次收到新关注者时都会向所有者发送电子邮件。我知道,有点多。

我猜我需要创建一个关注者列表,发送它,然后删除它以准备5个新关注者?我真的不知道该怎么做。非常感谢任何帮助或建议。

视图:

@login_required
# this is creating a follower. Maybe I shouldn't send the email through this?
def follow(request, id):
    company = Company.objects.get(id=id)
    profile = get_object_or_404(UserProfile, user__username=request.user.username)
    try:
        follower = Follower.objects.get(profile=profile, company=company)
        if not follower.verified:
            follower.verified = True
            follower.save() 
        messages.success(request, 'Now following %s\''%company.name)
        mes = Message(subject="New Follower", sender=profile, recipient=company.owner)
        mes.body = render_to_string('emails/email-message/new_follower.html', RequestContext(request, {
        'sender': profile,
        'receiver': company.owner,
        }))
    except ObjectDoesNotExist:
        messages.error(request, 'Failed to follow.')

1 个答案:

答案 0 :(得分:3)

每当特定公司的粉丝数量变为5的倍数时发送电子邮件,如下所示:

   if not (Follower.objects.filter(company=company).count() % 5):
        #send the email