Inconsistent types in PostgreSQL RangeFields

16 views
Skip to first unread message

francois-xa...@airinov.fr

unread,
Feb 14, 2017, 8:05:57 AM2/14/17
to Django users
Hello all,

I've been hitting a small annoyance when using the RangeField classes in the PostgreSQL contrib modules : while the value returned by psycopg is a psycopg.extras.Range type, the Django documentation explicitly mentions using tuples when creating and updating model instances.

This means that any method or property that has to process RangeFields must handle both tuples and Range types, which are incompatible.

For example, here is a very simple model :

    class MyModel(models.Model):

        range = DateTimeRangeField()

        def has_started_1(self):
            return self.range.lower() <= timezone.now()

        def has_started_2(self):
            return self.range[0] <= timezone.now()

In this naïve implementation, the `has_started_1` method will crash when used like this :

    instance = MyModel.objects.create(range=(timezone.now(), timezone.now() + timezone.timedelta(days=5))
    instance.has_started_1()  # Crash
    instance.has_started_2()  # True

...and the `has_started_2` method will crash with this :

    instance = MyModel.objects.last()
    instance.has_started_1()  # True
    instance.has_started_2()  # Crash

How should I handle that better?

Thanks for your help!
François-Xavier

Tim Graham

unread,
Feb 14, 2017, 9:24:06 AM2/14/17
to Django users
The documentation says, "All of the range fields translate to psycopg2 Range objects in python, but also accept tuples as input if no bounds information is necessary."

It looks to me like you could initialize the objects using psycopg's Range objects to eliminate the need to handle the tuple case. The tests have some examples: https://github.com/django/django/blob/master/tests/postgres_tests/test_ranges.py
Reply all
Reply to author
Forward
0 new messages