3

I want an "active_in" attribute as a timeframe. I assume that the DBMS is optimized for the postgresql tsrange field, and as such it is preferable to utilize the DateTimeRangeField rather than 2 separate fields for start_date and end_date.

Doing this I desire a default value for the field.

active_in = models.DateTimeRangeField(default=timezone.now+'-'+timezone.now+10YEARS)
  • Is my assumption about the DateTimeRangeField performance true?
  • Is there a smart solution be it creating a new; function,class or simply manipulating the 2nd last digit?

My possible solutions:

Code using string manipulation:

active_in = models.DateTimeRangeField(default=timezone.now+'-'+timezone.now[:-2]+'30')

Code using custom function object: (adjusted from here: https://stackoverflow.com/a/27491426/7458018)

def today_years_ahead():
    return timezone.now + '-' timezone.now() + timezone.timedelta(years=10)

class MyModel(models.Model):
    ...
    active_in = models.DateTimeRangeField(default=today_years_ahead)
LeOverflow
  • 301
  • 1
  • 2
  • 16

1 Answers1

4

There's no need for string manipulation, as the documented Python type for this field is DateTimeTZRange.

I can't say I've ever used this field before, but something like this should work:

from psycopg2.extras import DateTimeTZRange
from django.utils import timezone
from datetime import timedelta

def next_ten_years():
    now = timezone.now()

    # use a more accurate version of "10 years" if you need it
    return DateTimeTZRange(now, now + timedelta(days=3652))

class MyModel(models.Model):
    ...
    active_in = models.DateTimeRangeField(default=next_ten_years)
Kevin Christopher Henry
  • 46,175
  • 7
  • 116
  • 102