How should I use DurationField in my model?

前端 未结 1 644
无人共我
无人共我 2020-12-03 04:48

In my model I want to be able to input duration, like 2 years, 5 months, etc.

In version 1.8 DurationField was introduced so

相关标签:
1条回答
  • 2020-12-03 05:27

    To use a DurationField in django 1.8 you have to use a python datetime.timedelta instance like this:

    Considering this model :

    from django.db import models
    
    class MyModel(models.Model):
        duration = models.DurationField()
    

    You can set a duration this way :

    import datetime
    
    my_model = MyModel()
    my_model.duration = datetime.timedelta(days=20, hours=10)
    

    And query it this way :

    # Equal
    durations = MyModel.objects.filter(duration=datetime.timedelta(*args, **kwargs))
    
    # Greater than or equal
    durations = MyModel.objects.filter(duration__gte=datetime.timedelta(*args, **kwargs))
    
    # Less than or equal
    durations = MyModel.objects.filter(duration__lte=datetime.timedelta(*args, **kwargs))
    

    More info on datetime.timedelta here and on DurationField here.

    In your admin panel, you can enter a duration with a string with following format : [DD] [[hh:]mm:]ss

    0 讨论(0)
提交回复
热议问题