Oleg
Oleg

Reputation: 847

Django update model after condition

I have a model like this

class Foo(models.Model):
      bet = models.IntegerField()
      end_date = models.DateTimeField() \\some date in the future
      is_canceled = models.BooleanField(default=False)

I need automatically set is_canceled = True when end_date = datetime.now()

Upvotes: 0

Views: 72

Answers (1)

Sergey Gornostaev
Sergey Gornostaev

Reputation: 7807

You can create management command that will be periodically run from cron and change field value

now = datetime.now()
Foo.objects.filter(end_date__lte=now).update(is_canceled=True)

But it's better to make that field dynamic

class Foo(models.Model):
    bet = models.IntegerField()
    end_date = models.DateTimeField() \\some date in the future

    @property
    def is_canceled(self):
        if self.end_date <= datetime.now():
            return True
        else:
            return False

some_foo = Foo.objects.first()
if some_foo.is_canceled:
    ...

Upvotes: 3

Related Questions