django automated dateTime field
Hello i'm working on a blog app and I have a model:
class Post(models.Model):
title = models.CharField(max_length=255)
<..>
is_published = models.BooleanField(default=False)
time_publish = models.DateTimeField()
time_edit = models.DateTimeField(auto_now=True)
time_create = models.DateTimeField(auto_now_add=True)
And i want to set that, when user sets is_published=True
and .save()
is called then time_publish would save current time.
The problem is that i don't know what route i should take. Overwrite .save()
or make something with signals or what? I would appreciate some links t开发者_JAVA百科o Docs.
Sorry if it's dublicate but i din't knew how the question of such matter should be named.
Update:
So thanks to manji i produced this code that works:
def save(self, *args, **kwargs):
if self.pk is not None:
orig = Post.objects.get(pk=self.pk)
if not orig.time_publish and self.is_published:
self.time_publish = datetime.now()
elif not self.is_published:
self.time_publish = None
super(Post, self).save(*args, **kwargs)
The simplest solution (and django compliant) is to override your model's save
method.
class Post(models.Model):
...
def save(self, *args, **kwargs):
if self.is_published:
self.time_publish = datetime.now() # don't forget import datetime
super(Post, self).save(*args, **kwargs)
...
More informations here: Overriding predefined model methods
精彩评论