1

[Hopefully I entitled this post correctly]

I have a (sort of) 'follow' twitter thing going on. Users can follow a company profile object, which creates a follower object.

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

What I'd like to do is send an update email to the company profile owner, after 5 new followers. 'You have 5 new followers!'.

As of right now I'm sending an email to the owner every time they get a new follower. A little much, I know.

I'm guessing I need to create a list of followers, send it, and then delete it to prepare for 5 new followers? I'm really not sure how to go about this. Any help or suggestions are greatly appreciated.

view:

@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.')
Modelesq
  • 5,192
  • 20
  • 61
  • 88

1 Answers1

3

Send the email every time the number of followers for a specific company becomes a multiple of 5, like so:

   if not (Follower.objects.filter(company=company).count() % 5):
        #send the email
thikonom
  • 4,219
  • 3
  • 26
  • 30
  • I would still need to create a list of the 5 most recent followers, yes? – Modelesq Sep 11 '12 at 19:29
  • yes, as simple as Follower.objects.filter(company=company).order_by('-created')[:5], this will give you the last 5 and you won't need to delete anything. – thikonom Sep 11 '12 at 19:31
  • An other slightly more complicated option would be to use signals. Let me know if you want me to write this solution too, if this one does not fit you. – thikonom Sep 11 '12 at 19:34
  • I'm fairly new to django and haven't tackled signals. I'd love to see it! Thank you for your help! – Modelesq Sep 11 '12 at 19:36