Django - Populate DateTime field from other DateTimeField set with auto_now -
i'm trying populate last_version_date
modified
field set auto_now
. in save method, if new version created want save modified date record.
simplified example :
class poll(models.model): question = models.charfield(max_length=200) modified = models.datetimefield(auto_now=true) version = models.integerfield(blank=false, default=1) last_version_date = models.datetimefield(auto_now_add=true,blank=false) def save(self, keep_history=false, *args, **kwargs): if keep_history: self.last_version_date = self.modified self.version = self.version + 1 return super(poll, self).save(*args, **kwargs)
usage
>>> p = poll.objects.create(question = 'test1') >>> p.save() >>> p.modified datetime.datetime(2014, 8, 18, 6, 50, 41, 820000, tzinfo=<utc>) >>> p.last_version_date datetime.datetime(2014, 8, 18, 6, 50, 38, 381000, tzinfo=<utc>) >>> p.created datetime.datetime(2014, 8, 18, 6, 50, 38, 380000, tzinfo=<utc>) >>> >>> >>> p.save(true) >>> p.modified datetime.datetime(2014, 8, 18, 6, 51, 1, 804000, tzinfo=<utc>) >>> p.last_version_date datetime.datetime(2014, 8, 18, 6, 50, 41, 820000, tzinfo=<utc>)
notice how in second save last_version_date
being updated previous value of modified
.
looking @ source datetimefield
's auto_now
option see it's being populated in pre_save
hook expect value populated prior save.
thanks.
from django documentation :
datefield.auto_now_add
automatically set field when object first created. useful creation of timestamps. note current date used; it’s not default value can override.
if want have default time value of 'last_version_date' use 'default' key timezone.now function input
from django.utils import timezone class poll(models.model): .... last_version_date = models.datetimefield(default=timezone.now,blank=false)
see answer. save function can become
def save(self, *args, **kwargs): keep_history = kwargs.get('keep_history', false) if keep_history: self.last_version_date = self.modified self.version = self.version + 1
and use following
>>> p.save(keep_history=true)
you can use, concurrency, integerversionfield version field.
Comments
Post a Comment