在Django的午夜减少模型值 [英] Decrementing model value at midnight in Django
问题描述
我想在午夜每天将值days_till_study减1。
I want to decrement the value days_till_study with 1 everyday at midnight.
我目前的方法不是很优雅。有更好的方法吗?
My current approach is not very elegant. Is there a better way to do this?
from django.db import models
from django.utils import timezone
class Card(models.Model):
question = models.CharField(max_length=100)
answer = models.TextField()
date = models.DateTimeField(default=timezone.now)
creator = models.ForeignKey(User, on_delete=models.CASCADE)
decks = models.ManyToManyField(Deck)
days_till_study = models.IntegerField(default=1)
def __str__(self):
return self.question
def decrement_days_till_study(self):
if days_till_study < 1:
x = str(datetime.datetime.now())
if x[x[11:26]] == '00:00:00.000000':
days_till_study += 1
感谢阅读。
推荐答案
即时计算结果
如果您可以控制存储在数据库中的内容,最好将两天都存储在数据库中并根据它计算差异:
Calculating the result on the fly
If you have control over what to store in the database, it's better to store both days in the database and calculate the difference based on it:
class Card(models.Model):
created_at = models.DateTimeField()
study_at = models.DateTimeField()
@property
def days_till_study(self):
return (self.study_at - self.created_at).days
通过Celery计划
如果您仍然需要按计划执行某项操作(例如更新在午夜> days_till_study
),您可以尝试 django-cron 库或其他基于Celery的解决方案。
Scheduling via Celery
If you still need to do something by a schedule (like updating days_till_study
at midnight) you can try django-cron library or another Celery-based solution.
Also, you can create a management command and run it by a schedule via the system cron.
这篇关于在Django的午夜减少模型值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!