当DateTimeField等于当前日期和时间时,Django执行函数

时间:2018-10-12 09:28:52

标签: python django python-3.x

因此,我已经实现了我网站的订阅产品。

当他们开始订阅时,当前日期和时间将存储到数据库中。当他们取消订阅时,开始日期会加上一段时间,因此我知道何时取消订阅并在其他位置更改某些值。

这很好,我知道如何使用Django和Python,但是,当将来的取消日期到来时,我被困在最后。

问题:当取消日期(在数据库中)等于当前日期和时间时,如何执行功能。

以下是我将使用的模型的简单示例:

models.py

class Subscriptions(models.Model):
    subscription_id = models.AutoField(primary_key=True)
    start_date = model.DateTimeField(auto_now_add=True)
    cancel_date = model.DateTimeField(auto_now_add=False)
    person_id = model.ForeignKey('Persons')

class Persons(models.Model):
    person_id = models.AutoField(primary_key=True)
    value_to_change = models.BooleanField()

在您问我没有尝试任何代码之前,我找不到解决此问题的方法。谢谢<3

1 个答案:

答案 0 :(得分:2)

没有Celery,安装在提供CRON的UNIX系统上(cron doku:例如https://www.computerhope.com/unix/ucrontab.htm):

  1. 编写一个命令https://docs.djangoproject.com/en/2.1/howto/custom-management-commands/,以获取过去的cancel_date尚未被取消的对象。 (如果您使用datetime.now()(具有最佳粒度的非常精确的查找)进行查找,那么您将很幸运找到任何东西。)

您应该添加另一个日期字段,告诉您系统实际执行取消的时间,并且您应同时将cancel_date和cancelled_date都设置为空。

class Subscriptions(models.Model):
    subscription_id = models.AutoField(primary_key=True)
    start_date = model.DateTimeField(auto_now_add=True)
    cancel_date = model.DateTimeField(auto_now_add=False, null=True)
    cancelled_date = model.DateTimeField(null=True)
    person_id = model.ForeignKey('Persons')

class CancellationCommand(BaseCommand):
    def handle(self, *args, **options):
        now = datetime.now()
        to_cancel_qs = Subscriptions.objects.exclude(
            cancelled_date__isnull=False).filter(
            cancel_date__lte=now)
        for sub in to_cancel_qs.all():
            # do your cancelling
            sub.cancelled_date = now
            sub.save()
        # or: to_cancel_qs.update(cancelled_date=now)
  1. 安装一个cron作业,该作业会通过./manage.py your_command定期运行此命令