有没有办法在 Django 中保存或更新对象之前对其进行操作?

发布于 2024-11-29 06:10:50 字数 714 浏览 1 评论 0原文

根据 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧瑾黎汐 2024-12-06 06:10:50

设置 TIME_ZONE 怎么样?

要回答标题上的问题,您可以覆盖模型上的保存方法:

def save(self):
    # do stuff before save
    super(YourModel, self).save()
    # do stuff after save

如果您想通知其他人某些事件(例如保存前和保存后),请使用 django 信号

how about setting the TIME_ZONE?

To answer the question on the title, you can override the save method on your model:

def save(self):
    # do stuff before save
    super(YourModel, self).save()
    # do stuff after save

If you want to inform others about certain events (like pre-save and post-save), use django signals

薆情海 2024-12-06 06:10:50

嗯,如果我理解正确的话,我认为一个好的方法是创建一个自定义 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 subclass DateTimeField and override a few methods (to_python, pre_save, etc., it depends of your specific needs).

Check the documentation for more info.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文