在models.py中创建表结构时
from django.db import models class Book(models.Model): title = models.Charfield(max_length=32) date = models.Datefield(auto_now = True)
那么在更新数据是两种方法对auto_now的影响:
#(1)update方法: models.Book.objects.filter(title='asd').update(title='ads') #update方法不会改变date的时间,还是保存着创建时的时间点 #(2) .save()方法: obj = models.Book.objects.filter(title='asd').first() obj.title='ads' obj.save() #.save()方法是保存了更改时的时间点
如果我们当时设定的是auto_now_add=True时:
from django.db import models class Book(models.Model): title = models.Charfield(max_length=32) date = models.Datefield(auto_now_add = True)
此时,update方法和.save()方法对时间都是无效的。
那么我们如何手动的更改时间呢?
方法如下:
models.Book.objects.filter(title='asd').update(date=datetime.datetime.now())