0

I have a model like Main as shown below


    class Main(models.Model):
        Timestamp = models.DateTimeField(auto_now=True)
        name = models.CharField(max_length=100)
        .........................
        .........................

Main.objects.filter(id=1).update(name="abc") is updating the Timestamp to current datetime but when I use mysql query UPDATE Main SET name="abc" WHERE id=1 is not updating the Timestamp to current Datetime

Note: I want to use mysql query only.

Does anyone know how to do it?

Yurets
  • 3,999
  • 17
  • 54
  • 74
  • If you check the mysql schema you'll find that there's no default value being set for the field. If I'm not mistaken the auto_now only works when you save the model through a model manager. Try adding a default value such as in this answer: https://stackoverflow.com/questions/2771676/django-datetime-issues-default-datetime-now – Gerik Jul 02 '18 at 14:25
  • Try: `UPDATE Main SET name="abc", WHERE id=1` – t0bi Jul 02 '18 at 14:28
  • @gerik I need to delete auto_now and just add default value or I need to keep both – Janardhan Reddy. Meeniga Jul 02 '18 at 15:08
  • You know what: I apologize, I just realized this is for an update rather than for an insert. The default value is only set on new insertions. Since you're constructing your UPDATE statement via SQL you need to add the field which should be updated with the timestamp to your query. – Gerik Jul 02 '18 at 15:16
  • No It should update automatically when I update without timestamp using MySQL query. That is my requirement. – Janardhan Reddy. Meeniga Jul 02 '18 at 15:34
  • please check this: https://stackoverflow.com/questions/1737017/django-auto-now-and-auto-now-add – Diego Avila Jul 02 '18 at 16:11

0 Answers0