This is what I've pieced together so far. It seems like the most Django-esque way of doing this, but I'm happy to be corrected if not.
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
import datetime
class MyModel(models.Model):
is_active = models.BooleanField(default=False)
active_from = models.DateTimeField(blank=True)
# Set active_from if active is set in an update
@receiver(pre_save, sender=MyModel)
def set_active_from_on_update(sender, instance, update_fields, **kwargs):
if 'is_active' in update_fields and instance.is_active is True:
instance.active_from = datetime.now()
# Set active_from if active is set on create
@receiver(post_save, sender=MyModel)
def set_active_from_on_create(sender, instance, created, **kwargs):
if created and instance.is_active is True:
instance.active_from = datetime.now()
My reasoning: update_fields
in pre_save
seems like the right place for any logic based on particular fields updating, but pre_save
doesn't know if instance
will be a new entry in the database or not, so post_save
is needed to use the create
boolean.
I think I could also do away with is_active
and set active_from
to null
when it isn't active, but that doesn't seem as safe.