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.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With