有没有办法在 Django 中保存或更新对象之前对其进行操作?
根据 this 最近的问题,我需要将所有 datetime
对象存储在 UTC 中,所以我需要使用自定义库在存储它们之前正确翻译它们。有没有办法可以对即将保存和/或更新的对象进行操作,以便将 datetime
对象转换为 UTC?我希望这对我如何使用 Django 非常透明,所以如果它是这些类型的字段中的任何一种:
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
event_time = models.DateTimeField()
...我想将它们翻译为“幕后”,可以这么说,以免手动执行以下操作:
new_instance.created = translate(now)
new_instance.modified = translate(now)
new_instance.event_time = translate(event_time)
在所有 DateTimeField
字段上手动执行此操作很快就会变得非常麻烦。 Django 有办法做到这一点吗?在 Hibernate 中,我会使用 AOP 或拦截器来执行此操作。
As per this recent question, I'll be needing to store all datetime
objects in UTC, so I'll need to use a custom library to translate them properly before they're stored. Is there a way I can act on objects which are about to be saved and/or updated in order to convert the datetime
objects to UTC? I'd like this to be pretty transparent to how I use Django, so if it's any one of these types of fields:
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
event_time = models.DateTimeField()
...I'd like to translate them 'behind the scenes' so to speak, so as to not have to manually do the following:
new_instance.created = translate(now)
new_instance.modified = translate(now)
new_instance.event_time = translate(event_time)
It'd get pretty cumbersome pretty quickly to manually do this on all DateTimeField
fields. Is there a way in Django to do this? In Hibernate, I'd either use AOP or an Interceptor
to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
设置 TIME_ZONE 怎么样?
要回答标题上的问题,您可以覆盖模型上的保存方法:
如果您想通知其他人某些事件(例如保存前和保存后),请使用 django 信号
how about setting the TIME_ZONE?
To answer the question on the title, you can override the save method on your model:
If you want to inform others about certain events (like pre-save and post-save), use django signals
看看信号: https://docs.djangoproject.com/en/1.3/主题/信号/
Have a look at Signals: https://docs.djangoproject.com/en/1.3/topics/signals/
嗯,如果我理解正确的话,我认为一个好的方法是创建一个自定义
DateTimeField
。为此,您应该子类化DateTimeField
并重写一些方法(to_python、pre_save 等,这取决于您的具体需求)。有关更多信息,请查看文档。
Hmm, if I understand you correctly, I think a good way to go will be to create a custom
DateTimeField
. For that you should subclassDateTimeField
and override a few methods (to_python, pre_save, etc., it depends of your specific needs).Check the documentation for more info.