简体   繁体   中英

Adjust Choice in Django CharField using Current Date

I am working on a Django project where my models.py file looks like this:

STATUS = (
    ('Active', 'Active'),
    ('Inactive', 'Inactive')
)

class ClassName(models.Model):
    ...
    deadline = models.DateTimeField('Deadline')
    status = models.CharField(max_length=10, choices=STATUS)

What I'd like to do is change the status from Active to Inactive if the current date is greater than the date entered for the deadline. Anyone know how I might accomplish this?

You can override Model.save() method to adjust your fields that depend on each other:

from django.utils import timezone

class ClassName(models.Model):
    ...
    deadline = models.DateTimeField('Deadline')
    status = models.CharField(max_length=10, choices=STATUS)

    def save(self, *args, **kwargs):
        if self.deadline < timezone.now():
            self.status = 'Inactive'
        super(ClassName, self).save(*args, **kwargs)

To fix previously created instances, you can do the following in your python shell:

ClassName.objects.filter(deadline__lt=timezone.now()).update(status='Inactive')

This will mark all ClassName instances as inactive whose deadline is less than timezone.now() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM