How to put timedelta in django model?

后端 未结 7 1375
情歌与酒
情歌与酒 2020-12-09 14:29

With inspectdb I was able to get a \"interval\" field from postgres into django. In Django, it was a TextField. The object that I retrieved was indeed a timedelta object!

7条回答
  •  隐瞒了意图╮
    2020-12-09 15:03

    First, define your model:

    class TimeModel(models.Model):
        time = models.FloatField()
    

    To store a timedelta object:

    # td is a timedelta object
    TimeModel.objects.create(time=td.total_seconds())
    

    To get the timedelta object out of the database:

    # Assume the previously created TimeModel object has an id of 1
    td = timedelta(seconds=TimeModel.objects.get(id=1).time)
    

    Note: I'm using Python 2.7 for this example.

提交回复
热议问题