Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django's DateTimeField's "auto_now" doesn't seem to work

I have a Comment model. It has following timestamp fields:

created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
last_edit = models.DateTimeField(auto_now=True, blank=True, null=True)

Now when I update a comment using this format: Comment.objects.filter(...).update(text="some new text"), the last_edit field doesn't get updated while the text of the comment does get updated. What's the issue?

Update: Also, I am using filter because update doesn't work with get, i.e., Comment.objects.get(...).update(...) won't work. What I actually want to do is get because I am sure only one comment has to updated at one time.

like image 554
kamalbanga Avatar asked Jun 06 '15 11:06

kamalbanga


1 Answers

Because you're using update, which does the update directly in the database, whereas auto_now is done in Python. This would work:

for commment in Comment.objects.filter(...):
    comment.text="some new text"
    comment.save()

Obviously, this is less efficient than doing it in one go in the db. If you really need that, then you'd have to set the date in the update as well:

Comment.objects.filter(...).update(text="some new text", last_edit=datetime.datetime.now())
like image 83
Daniel Roseman Avatar answered Nov 14 '22 23:11

Daniel Roseman