django model:auto_now_add 和 auto_now
创建django的model时,有DateTimeField、DateField和TimeField三种类型可以用来创建日期字段,其值分别对应着datetime()、date()、time()三中对象。这三个field有着相同的参数auto_now和auto_now_add,并且在实际使用中很容易出错,下面是一些注意点。
DateTimeField.auto_now
auto_now = True # 这个参数的默认值为false,设置为true时,能够在保存该字段时,将其值设置为当前时间,并且每次修改model,都会自动更新。因此这个参数在需要存储“最后修改时间”的场景下,十分方便。需要注意的是,设置该参数为true时,并不简单地意味着字段的默认值为当前时间,而是指字段会被“强制”更新到当前时间,你无法程序中手动为字段赋值;如果使用django再带的admin管理器,那么该字段在admin中是只读的
DateTimeField.auto_now_add
auto_now_add = True # 这个参数的默认值也为False,设置为True时,会在model对象第一次被创建时,将字段的值设置为创建时的时间,以后修改对象时,字段的值不会再更新。该属性通常被用在存储“创建时间”的场景下。与auto_now类似,auto_now_add也具有强制性,一旦被设置为True,就无法在程序中手动为字段赋值,在admin中字段也会成为只读的。
admin中的日期时间字段
auto_now和auto_now_add被设置为True后,这样做会导致字段成为editable=False和blank=True的状态。editable=False将导致字段不会被呈现在admin中,blank=Ture表示允许在表单中不输入值。此时,如果在admin的fields或fieldset中强行加入该日期时间字段,那么程序会报错,admin无法打开;如果在admin中修改对象时,想要看到日期和时间,可以将日期时间字段添加到admin类的readonly_fields中:
class YourAdmin(admin.ModelAdmin):
readonly_fields = ('save_date', 'mod_date',)
admin.site.register(Tag, YourAdmin)
如何将创建时间设置为“默认当前”并且可修改
那么问题来了。实际场景中,往往既希望在对象的创建时间默认被设置为当前值,又希望能在日后修改它。怎么实现这种需求呢?
django中所有的model字段都拥有一个default参数,用来给字段设置默认值。可以用default=timezone.now来替换auto_now=True或auto_now_add=True。timezone.now对应着django.utils.timezone.now(),因此需要写成类似下面的形式:
from django.db import models
import django.utils.timezone as timezone
class Doc(models.Model):
add_date = models.DateTimeField('保存日期',default = timezone.now)
mod_date = models.DateTimeField('最后修改日期', auto_now = True)
html页面从数据库中读出DateTimeField字段时,显示的时间格式和数据库中存放的格式不一致,比如数据库字段内容为2016-06-03 13:00:00,但是页面显示的却是Apr. 03, 2016, 1 p.m.
为了页面和数据库中显示一致,需要在页面格式化时间,需要添加<td>{{ infor.updatetime|date:"Y-m-d H:i:s" }}</td> 类似的过滤器。刷新页面,即可正常显示。
官方文档:
DateField
class DateField(auto_now=False, auto_now_add=False, **options)
A date, represented in Python by a datetime.date instance. Has a few extra, optional arguments: DateField.auto_now
Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override. The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that. DateField.auto_now_add
Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True: 1. For DateField: default=date.today - from datetime.date.today()
# For DateTimeField: default = datetime.now # 不要加 () # - from datetime.datetime.now()
2. For DateTimeField: default=timezone.now - from django.utils.timezone.now()
The default form widget for this field is a TextInput. The admin adds a JavaScript calendar, and a shortcut for “Today”. Includes an additional invalid_date error message key. The options auto_now_add, auto_now, and default are mutually exclusive. Any combination of these options will result in an error. """
Note As currently implemented, setting auto_now or auto_now_add to True will cause the field to have editable=False and blank=True set
""" """
Note The auto_now and auto_now_add options will always use the date in the default timezone at the moment of creation or update. If you need something different, you may want to consider simply using your own callable default or overriding save() instead of using auto_now or auto_now_add; or using a DateTimeField instead of a DateField and deciding how to handle the conversion from datetime to date at display time.
"""
django model:auto_now_add 和 auto_now的更多相关文章
- Django中 auto_now_add 和 auto_now 的区别
auto_now_add = True #创建时添加的时间 修改数据时,不会发生改变 auto_now = True #修改数据的时间,每次修改都会有变动 ........
- 【转】Django Model field reference学习总结
Django Model field reference学习总结(一) 本文档包含所有字段选项(field options)的内部细节和Django已经提供的field types. Field 选项 ...
- Django model字段类型清单
转载:<Django model字段类型清单> Django 通过 models 实现数据库的创建.修改.删除等操作,本文为模型中一般常用的类型的清单,便于查询和使用: AutoField ...
- Django Model field reference
===================== Model field reference ===================== .. module:: django.db.models.field ...
- Django学习之四:Django Model模块
目录 Django Model 模型 MODEL需要在脑子里记住的基础概念 区分清楚,必须不能混淆的 class Meta 内嵌元数据定义类 简单model创建实例 数据源配置 接着通过models在 ...
- django model数据 时间格式
from datetime import datetime dt = datetime.now() print '时间:(%Y-%m-%d %H:%M:%S %f): ' , dt.strftime( ...
- Django model转字典的几种方法
平常的开发过程中不免遇到需要把model转成字典的需求,尤其是现在流行前后端分离架构,Json格式几乎成了前后端之间数据交换的标准,这种model转dict的需求就更多了,本文介绍几种日常使用的方法以 ...
- Django model 字段类型清单
Django model字段类型清单 Django 通过 models 实现数据库的创建.修改.删除等操作,本文为模型中一般常用的类型的清单,便于查询和使用: AutoField 一个自动递增的整型字 ...
- Django Model 基础数据库操作应用
https://blog.csdn.net/Mrzhangjwei/article/details/53001841 一.数据库操作1.创建model表 基本结构: from django.db im ...
- Django model总结(上)
Django model是django框架中处于比较核心的一个部位,准备分三个博客从不同的方面分别进行阐述,本文为<上篇>,主要对[a]Model的基本流程,比如它的创建,迁移等:默认行为 ...
随机推荐
- C# DateTime的使用
获得当前系统时间: DateTime dt = DateTime.Now; Environment.TickCount可以得到“系统启动到现在”的毫秒值 DateTime now = DateTime ...
- mod_deflate模块
mod_deflate模块 压缩模块,使用mod_deflate模块压缩页面优化传输速度 主要是需要设置 1.针对的内容 2.压缩比是多少 可以忽略排除特定旧版本的浏览器的设置.因为那些都太老了,现在 ...
- Cluster - 基本概念
1.1 什么是集群 简单的说,集群(cluster)就是一组计算机,它们作为一个整体向用户提供一组网络资源.这些单个的计算机系统就是集群的节点(node).一个理想的集群是,用户从来不会意识到集群系统 ...
- html5支持drag的拖放排序插件sortable.js
html5支持drag的拖放排序插件sortable.js <script src="//cdnjs.cloudflare.com/ajax/libs/Sortable/1.5.1/S ...
- ZendFramework-2.4 源代码 - 关于MVC - Controller层
// 1.控制器管理器 class ServiceManager implements ServiceLocatorInterface { public function __construct(Co ...
- JZOJ 5812. 【NOIP提高A组模拟2018.8.14】 区间
5812. [NOIP提高A组模拟2018.8.14] 区间 (File IO): input:range.in output:range.out Time Limits: 1000 ms Memo ...
- for循环+canvas实现黑客帝国矩形阵
<!DOCTYPE html><html><head> <meta http-equiv="Content-Type" content=& ...
- HihoCoder - 1636 Pangu and Stones(区间DP)
有n堆石子,每次你可以把相邻的最少L堆,最多R堆合并成一堆. 问把所有石子合并成一堆石子的最少花费是多少. 如果不能合并,输出0. 石子合并的变种问题. 用dp[l][r][k]表示将 l 到 r 之 ...
- CyclicBarrier源码分析
CyclicBarrier是通过ReentrantLock(独占锁)和Condition来实现的.下面,我们分析CyclicBarrier中3个核心函数: 构造函数, await()作出分析. 1. ...
- VMware之无法切换桥接网络
一.关闭正在运行的虚拟机 二.打开虚拟网络编辑器 三.还原默认设置 四.启动虚拟机即可正常使用桥接网络