显示情况下,在django admin后台,具有自动更新的日期字段,是不会显示在后台的。那如何显示出来呢?
一,django model中的定义
class BaseModel(models.Model):
name = models.CharField(max_length=100,
unique=True,
verbose_name="名称")
description = models.CharField(max_length=100,
null=True,
blank=True,
verbose_name="描述")
create_user = models.ForeignKey(User,
blank=True,
null=True,
on_delete=models.SET_NULL,
verbose_name="用户")
update_date = models.DateTimeField(auto_now=True)
create_date = models.DateTimeField(auto_now_add=True)
base_status = models.BooleanField(default=True)
history = HistoricalRecords(inherit=True)
- create_date 会在第一次增加时记录日期,
- update_date 会在每一次更新时,自动更新日期(有条件调用语句)。
- 这两个字段,默认情况,不会在django admin后台管理界面上显示。
二,在admin.py中增加配置
class ReleaseHistoryHistoryAdmin(SimpleHistoryAdmin):
list_display = ['id', 'name', 'release', 'env', 'deploy_status', 'deploy_type', 'log']
history_list_display = ["status"]
search_fields = ['name', 'release', 'log']
readonly_fields = ('create_date', 'update_date')
admin.site.register(ReleaseHistory, ReleaseHistoryHistoryAdmin)
-
readonly_fields的配置是关键,因为自动日期具有不可编辑的内在属性。
三,此时方可显示
2021-01-24 09_04_28-悬浮球.png
四,原理说法
https://docs.djangoproject.com/en/dev/ref/models/fields/#datefield
`
As currently implemented, setting auto_now or auto_now_add to True will cause the field to have editable=False and blank=True set.
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 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.
`
网友评论