Django模型在两个DateTimeFields之间经过的时间 [英] Django model elapsed time between two DateTimeFields

查看:136
本文介绍了Django模型在两个DateTimeFields之间经过的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对django刚起步,还无法找到一种方法来获取两个DateTimeFields之间的经过时间并将其保存到另一个模型中。

I am pretty new to django and haven't been able to find a way to get the elapsed time between two DateTimeFields and save it to another model.

from django.db import models



class Timesheet(models.Model):
    startTime = models.DateTimeField(auto_now_add=True)
    endTime = models.DateTimeField(blank=True, null=True)
    duration = models.DateTimeField(endTime - startTime)

    def _str_(self):
        return self.startTime

如何使工期= endTime-startTime?
我也在使用PostgreSQL数据库。

How can I make duration = endTime - startTime? I am also using a PostgreSQL database.

推荐答案

在此期间,我不会使用专用的模型字段。

I wouldn't use a dedicated model field for the duration.

我会在模型上使用属性代替相同的功能。

I would use a property on the model instead for the same functionality.

类似的东西:

@property
def duration(self)
    return self.end_time - self.startime

卢卡斯有一个很好的主意使用注释,但是如果某个Timesheet实例不是来自该对象管理器的,并且之前未进行注释,则必须进行单独的数据库匹配才能真正对其进行注释。

Lucas has a good idea of using an annotation, but if you have a Timesheet instance somewhere that didn't come from that object manager and was not previously annotated, you would have to do a separate database hit to actually annotate it.

该属性的用法如下:

some_timesheet_instance.duration

这篇关于Django模型在两个DateTimeFields之间经过的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆