当前位置:首页 » python web » 正文

django model的update时auto_now不被更新的原因及解决方式

看: 947次  时间:2020-07-25  分类 : python web

gmt_create自动添加auto_now_add;gmt_modify自动更新auto_now

class CommonInfo(models.Model):
"""基类,提供共同信息,不会创建真实的table"""

class Meta:
  # 声明自己为抽象基类
  abstract = True
  # 下面表示先根据更新时间gmt_modify降序排序,如果更新时间相同,再根据创建时间gmt_create降序排序
  ordering = ['-gmt_modify', '-gmt_create']

gmt_create = models.DateTimeField('创建时间,自动创建', auto_now_add=True, null=True, help_text='创建时间')
# 使用save可以达到自动更新的效果,使用update不会自动更新,因此需要携带上这个字段
gmt_modify = models.DateTimeField('更新时间,自动更新', auto_now=True, null=True, help_text='更新时间')

django的orm关于更新数据库的方法有update和save两种方法。

使用save时会自动更新

obj = User.objects.get(id=1)
obj.name='xxx'
obj.save()

save()时确实会自动更新当前时间

这是因为这个操作它经过了model层

使用update不会自动更新;因此需要在使用filter的update更新的时候同时赋值时间为datetime.datetime.now()

如果用django filter的update(通常为批量更新数据时)则是因为直接调用sql语句 不通过 model层

User.objects.filter(id=1).update(username='xxx')

补充知识:Django的auto_now=True没有自动更新

auto_now=True自动更新,有一个条件,就是要通过django的model层。

如create或是save方法。

如果是filter之后update方法,则直接调用的是sql,不会通过model层,

所以不会自动更新此时间。官方解释:

What you consider a bug, others may consider a feature, e.g. usingupdate_fieldsto bypass updating fields withauto_now. In fact, I wouldn't expectauto_nowfields to be updated if not present inupdate_fields.

解决办法:

强制改成save()或是update时,带上时间。

如下:

  status_item = DeployStatus.objects.get(name=status_name)
  DeployImage.objects.filter(name=order_name).update(
    deploy_status=status_item,
    change_date=datetime.now())

  # 上面的操作,才会更新DeployImage表里的change_date(add_now=True)的时间,
  # 或是如下调用save()方法
  # deploy_item = DeployImage.objects.get(name=order_name)
  # deploy_item.deploy_status = status_item
  # deploy_item.save()

以上这篇django model的update时auto_now不被更新的原因及解决方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

标签:django  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!