我有当前代码:
# ...
from django.utils import timezone
class Order(models.Model):
# ...
pay_date = models.DateTimeField(blank=True, null=True)
# ...
def pay(self):
# ...
self.pay_date = timezone.now()
self.save()
我在事务块中调用pay
方法:
# in one view func.
with transaction.atomic():
# ...
order.pay()
之后 - 没有任何事情发生,pay_date
字段仍为None
。
我尝试直接从控制台设置pay_date
字段,然后就可以了。
UPD:
我还尝试在pre_save
信号中设置日期,但它仍然无效(状态已更改,顺便说一句):
@reciever(pre_save, sender=Order)
def set_pay_date(sender, instance, **kwargs):
# check the special condition
old_order = Order.objects.get(id=instance.pk)
if old_order.state == States.NEW and instance.state == States.PAID:
instance.pay_date = timezone.now()