首页 > 解决方案 > 如何使用 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)

标签: djangodjango-models

解决方案


为了实现您的目标,您需要定期执行一个功能,检查实际日期 - 订单已下(创建)> 1 天的日期,然后将状态更改为“取消”。

1) 使用 django-cellerydjango-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

推荐阅读