0

有什么方法可以查看用户是否在一段时间内处于非活动状态?例如,在一段时间不活动后,Twitter 会向其用户发送一封电子邮件。我想实现一个类似的功能,如果用户已经 30 天不活动,则会发送一封电子邮件“你好用户,看看你的朋友发布了什么”我该如何实现这个?

4

4 回答 4

1

好吧,django.contrib.auth.models.User有一个last_login可能对你有用的领域。

就在您想要的任何地方,检查last_login日期,User您现在就会知道他离开您的网站多长时间了。

希望这可以帮助!

于 2013-05-28T16:34:00.057 回答
1

您可以编写一个管理命令来检查用户上次登录的时间,如果天数大于 30,则发送电子邮件。(您可以将其实现为每天运行的 cron)

import datetime
from django.core.management.base import BaseCommand

def compute_inactivity():
    inactive_users = User.objects.filter(last_login__lt=datetime.datetime.now() - datetime.timedelta(months=1))
    #send out emails to these users

class Command(BaseCommand):

    def handle(self, **options):
       compute_inactivity()

如果您有任何其他定义“活动”的标准,您可以根据它过滤您的查询集。

于 2013-05-28T16:31:48.837 回答
0

我的方法是在用户上次登录后的 30 天后准确地向用户发送通知。为此,您需要创建一个管理命令并将其作为每天的 cron 作业运行。

import datetime
from django.core.management.base import BaseCommand

def compute_inactivity():
    a_month_ago = datetime.datetime.now() - datetime.timedelta(days=30)
    inactive_users = User.objects.filter(
        last_login__year=a_month_ago.year,
        last_login__month=a_month_ago.month,
        last_login__day=a_month_ago.day,
        ) 
    #send out emails to these users

class Command(BaseCommand):
    def handle(self, **options):
        compute_inactivity()
于 2013-05-30T22:48:49.477 回答
0

在阅读了 karthikr 的回答和 Aidas Bendoraitis 的建议后,我在下面编写了更正解决方案。它与 Karthikr 的答案非常相似,只是不使用 __lt 丰富的比较运算符,而是使用 __eq 运算符:

import datetime
from django.core.management.base import BaseCommand

def compute_inactivity():
    inactive_users = User.objects.filter(last_login__eq=datetime.datetime.now() - datetime.timedelta(months=1))
    #send out emails to these users

class Command(BaseCommand):

def handle(self, **options):
    compute_inactivity()
于 2013-05-29T21:44:06.173 回答