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的基本流程,比如它的创建,迁移等:默认行为 ...
随机推荐
- oracle数据库删除表时遇见需要解锁问题
今天在进行数据清空时,不注意把表锁住了,记录一下解锁过程. 第一步执行 select t2.username,t2.sid,t2.serial#,t2.logon_time from v$locked ...
- 2.3.3 zerosum 和为零
#include<bits/stdc++.h> using namespace std; ],a; ]={' ','+','-'}; void out() { ;i<a;i++) c ...
- tab菜单的点击的动态效果和内容页面的关联显示jQuery
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- [Wolfgang Mauerer] 深入linux 内核架构 第二章 进程管理与调度【未完】
作为Linux开发爱好者,从事linux 开发有三年多时间.做过bsp移植,熟悉u-boot代码执行流程:看过几遍<linux 设备驱动程序开发>,分析过kernel启动流程,写过驱动, ...
- Git笔记(流水账)
命令git checkout -- readme.txt意思就是,把readme.txt文件在工作区的修改全部撤销,这里有两种情况: 一种是readme.txt自修改后还没有被放到暂存区,现在,撤销修 ...
- JZOJ 3385. 【NOIP2013模拟】黑魔法师之门
3385. [NOIP2013模拟]黑魔法师之门 (Standard IO) Time Limits: 1000 ms Memory Limits: 131072 KB Detailed Limi ...
- libevent源码分析1 ----evnet相关结构体分析
位于代码event-internal.h中. event_base类似事件的集合,你创建一个事件,必须将该事件指定一个集合. struct event_base { 50 const stru ...
- mac terminal基本命令
文件目录 首先要清楚几个文件目录: " / " :根目录 " ~ " :用户主目录的缩写.例如当前用户为esther,那么" ~ "展开来 ...
- android/libs/libammsdk.jar" already exists! 解决方法
Error: Uh oh!"/work/2016/fengkongbao/.meteor/local/cordova-build/platforms/android/libs/libamms ...
- P3376 【模板】网络最大流dinic算法
P3376 [模板]网络最大流 题目描述 如题,给出一个网络图,以及其源点和汇点,求出其网络最大流. 输入输出格式 输入格式: 第一行包含四个正整数N.M.S.T,分别表示点的个数.有向边的个数.源点 ...