How to put timedelta in django model?

后端 未结 7 1386
情歌与酒
情歌与酒 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:13

    There is a ticket which dates back to July 2006 relating to this: https://code.djangoproject.com/ticket/2443

    Several patches were written but the one that was turned in to a project: https://github.com/johnpaulett/django-durationfield

    Compared to all the other answers here this project is mature and would have been merged to core except that its inclusion is currently considered to be "bloaty".

    Personally, I've just tried a bunch of solutions and this is the one that works beautifully.

    from django.db import models
    from durationfield.db.models.fields.duration import DurationField
    
    class Event(models.Model):
        start = models.DateTimeField()
        duration = DurationField()
    
        @property
        def finish(self):
            return self.start + self.duration
    

    Result:

    $ evt = Event.objects.create(start=datetime.datetime.now(), duration='1 week')
    $ evt.finish
    Out[]: datetime.datetime(2013, 6, 13, 5, 29, 29, 404753)
    

    And in admin:

    Change event

    Duration: 7 days, 0:00:00

提交回复
热议问题