[英]How convert epoch time integerfield to datetime field in django admin
I use django and for saving time I am using epoch time
in an IntegerField
so my model is like this:我使用 django,为了节省时间,我在IntegerField
使用了epoch time
,所以我的模型是这样的:
class MyModel(models.Model):
start_time = models.IntegerField()
and start_time in admin is like this: admin 中的 start_time 是这样的:
It's not a problem but it's hard to check and update field for a person so my question is how can I convert this IntegerField
to DateTimeField
in django admin without changing my model?这不是问题,但很难检查和更新一个人的字段,所以我的问题是如何在 django admin 中将此IntegerField
转换为DateTimeField
而不更改我的模型? I know I can represent this field as readonly field and convert epoch time to DateTime but how can i use django admin DateTime picker?我知道我可以将此字段表示为只读字段并将纪元时间转换为 DateTime 但我如何使用 django admin DateTime 选择器?
I found my answer hope it help someone else, it's work but maybe it's not the best answer.我找到了我的答案,希望它可以帮助其他人,这是可行的,但也许不是最好的答案。
I used an intermediate field because I couldn't change the real field so I create a form to have a DateTimeField:我使用了一个中间字段,因为我无法更改实际字段,所以我创建了一个具有 DateTimeField 的表单:
from django import forms
from django.contrib.admin.widgets import AdminSplitDateTime
class MyModelAdminForm(forms.ModelForm):
start_date_time = forms.SplitDateTimeField(widget=AdminSplitDateTime())
class Meta:
model = MyModel
fields = '__all__'
then I add form to my admin:然后我将表单添加到我的管理员:
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
form = MyModelAdminForm
fields = ('start_date_time',)
for setting initial value of previous saved object in form:用于在表单中设置先前保存的对象的初始值:
def get_form(self, request, obj=None, **kwargs):
form = super().get_form(request, obj, **kwargs)
if obj:
form.base_fields['start_date_time'].initial = datetime.datetime.fromtimestamp(obj.start_time)
return form
the result is:结果是:
and last step is saving DateTimeField to IntegerField as epoch time:最后一步是将 DateTimeField 保存到 IntegerField 作为纪元时间:
def save_model(self, request, obj, form, change):
obj.start_time = round(form.cleaned_data['start_date_time'].timestamp())
obj.save()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.