django - 如何使用 Django 根据特定时间段更改模型字段?
问题描述
我想自动对我的模型进行一些更改。在这里,下新订单后,如果在下订单后 1 天内 isPaid 未变为真,我想更新订单状态以取消。我怎样才能做到这一点?
class Order(models.Model):
PENDING_PAYMENT = 'PENDING_PAYMENT'
status_choices = [
('CANCEL', 'Cancel'),
('PENDING_PAYMENT', 'Pending Payment'),
('ON_HOLD', 'On Hold'),
('WAITING_FOR_PAYMENT', 'Waiting For Payment'),
('PROCESSING', 'Processing'),
('DONE', 'Done'),
]
Ordinary = 'Ordinary'
customer_choices = [
('Ordinary', 'Ordinary'),
('Police', 'Police'),
('RAB', 'RAB'),
('DGIF', 'DGIF'),
('CID', 'CID'),
('NAVY', 'NAVY'),
('Air Force', 'Air Force'),
('Army', 'Army'),
('DB', 'DB'),
('Administration', 'Administration'),
]
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
paymentMethod = models.CharField(max_length=200, null=True, blank=True)
taxPrice = models.DecimalField(max_digits=11, decimal_places=2, null=True, blank=True)
shippingPrice = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
totalPrice = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True)
isPaid = models.BooleanField(default=False)
paidAt = models.DateTimeField(auto_now_add=False, null=True, blank=True)
isDelivered = models.BooleanField(default=False)
deliverAt = models.DateTimeField(auto_now_add=False, null=True, blank=True)
createdAt = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=220, choices=status_choices, default=PENDING_PAYMENT)
customerType = models.CharField(max_length=200, blank=True, null=True, choices=customer_choices, default=Ordinary)
_id = models.AutoField(primary_key=True, editable=False)
def __str__(self):
return str(self._id)
解决方案
为了实现您的目标,您需要定期执行一个功能,检查实际日期 - 订单已下(创建)> 1 天的日期,然后将状态更改为“取消”。
1) 使用 django-cellery:django-celery为 Django 提供了 Celery 集成。您将能够定期运行任务(功能)。
2) 定期运行的功能 这里是您可以运行检查的任务/功能的示例
from datetime import timedelta, datetime
from your_app.models import Order
def cancel_order():
# Retrieve the pending orders
pending_orders = Order.objects.filter(status='PENDING_PAYMENT')
# Loop and cancel unpaid order > 1 day
for order in pending_orders:
# if the time today is greater than order created date + 1 day
if datetime.today() > (order.createdAt + timedelta(days=1)):
order.status = 'CANCEL'
order.save()
# You can also write this action in a log file too
推荐阅读
- javascript - 如何发出经过身份验证的 Cognito 请求
- python - 返回两个列表之间匹配的一组索引
- python - 如何确定字符串变量是否位于目标变量的中间、开头或结尾
- vue.js - FontAwesome 无法在未定义的道具上使用 Vue3/TS
- r - 如何使用填充和颜色 geom_col vs geom_point
- python - 使用 Python 和 Scrapy 进行站点审计
- asp.net-mvc - TinyMCE 5.7.0 - 无法读取未定义的属性“isTouch”
- c - 在 C 语言中将字符串转换为简单的单字符值
- svelte - Svelte 如何在每个循环中处理更新数组中的对象
- loopbackjs - Loopback 4 cli 指令语言 - 如何重置