Reputation: 6921
I want to have some kind of timestsamp for updating of models. The problem is that mysql timestamp is only in 1 sec resolution, so if I use DateTime with auto_add_now this is not fine enough for me.
I thought of using float field and to assign it to time.time() on every update. This is a model where I use update using QuerySet.update()
model MyModel:
last_update = models.FloatField(default=time.time)
I then take care of updating last_update before any save (all my calls goes through central location, so I can do this explicitly in the creation), e.g something like:
m = MyModel(..,last_update=time.time())
or when I do bulk update,
m = MyModel.objects.filter(....).update(last_update_time=time.time())
Are there any issues with this approach of saving float and order by it?
Just to clarify, I'm aware of DateTimeField option with auto_now=True, the problem is that this gives me 1 second resolution since it is mapped to date time field in MYSQL which is 1 sec resolution (I'm using MYSQL 5.5)
Upvotes: 0
Views: 6074
Reputation: 774
I think you can use DateField.auto_now
, and the field will be updated each time the object gets saved. For example last_update = models.DateTimeField(auto_now = True)
.
You can read the documentation here, as you can see that Field option is intended to archive exactly what you want.
Also you can override the save
method as you can see there and update the last_update
field as you prefer.
Personally I recommend the first approach because of simplicity, there is also a third option using signals but I guess that can get so confusing.
Upvotes: 3
Reputation: 22808
from datetime import datetime
class Model(models.Model):
date_created = models.DateTimeField()
date_modified = models.DateTimeField()
def save(self):
if self.date_created == None:
self.date_created = datetime.now()
self.date_modified = datetime.now()
super(Model, self).save()
Upvotes: 1