如何在Django中选择时触发事件?

时间:2018-12-04 16:17:04

标签: python django

无论何时SAIDA_CHOICES为“ Sim”,它都不会执行任何操作,但当其为“Não”时,它会给出是,并使用datatimenow将其存储在数据库Checkout中。

但是,当我在Sim或Não中执行以下代码时,它始终存储结帐信息:

SAIDA_CHOICES = (
    ('Não', 'Não Pago'),
    ('Sim', 'Pago')
    )

class MovRotativo(models.Model):
    checkin = models.DateTimeField(auto_now=True, blank=False, null=False,)
    checkout = models.DateTimeField(auto_now=True, null=True, blank=True)
    email = models.EmailField(blank=False)
    placa = models.CharField(max_length=7, blank=False)
    modelo = models.CharField(max_length=15, blank=False)
    valor_hora = models.DecimalField(
         max_digits=5, decimal_places=2, null=False, blank=False)
    pago = models.CharField(max_length=15, choices=PAGO_CHOICES)
    chk = models.CharField(max_length=15, choices=SAIDA_CHOICES)

     def saida(self):
        if self.chk == 'sim':
            return self.chk
        else:
            self.checkout = models.DateTimeField(auto_now=True)
            return self.checkout

1 个答案:

答案 0 :(得分:1)

我认为您可以覆盖模型的save方法,以便如果该值不是Nao,则它将结帐值存储到当前时间:

from django.utils import timezone

class MovRotativo(models.Model):
    ...
    checkout = models.DateTimeField(default=None, null=True, blank=True)  # change it to default None
    ... # rest of the fields

    def save(self, *args, **kwargs):
        if not self.chk == 'Sim':
            self.checkout = timezone.now()
        else:
            self.checkout = None
        return super(MovRotativo, self).save(*args, **kwargs)