Truncate consecutive values in a Django (TimescaleDB) QuerySet

I have a QuerySet consisting of a timestamp and a boolean value. When there are consecutive repeating values, I'd like to truncate them to only show the first (and maybe the last one too, but not mandatory).

e.g. the given queryet

<TimescaleQuerySet [
{'time': datetime.datetime(2023, 1, 23, 10, 57, 7, 971506, tzinfo=<UTC>), 'is_on': True},
{'time': datetime.datetime(2023, 1, 23, 10, 53, 11, 787303, tzinfo=<UTC>), 'is_on': True}, 
{'time': datetime.datetime(2023, 1, 23, 10, 53, 20, 646474, tzinfo=<UTC>), 'is_on': False}, 
{'time': datetime.datetime(2023, 1, 23, 10, 27, 7, 971506, tzinfo=<UTC>), 'is_on': False}, 
{'time': datetime.datetime(2023, 1, 23, 10, 23, 20, 646474, tzinfo=<UTC>), 'is_on': False}, 
{'time': datetime.datetime(2023, 1, 23, 10, 23, 11, 787303, tzinfo=<UTC>), 'is_on': True}, 
{'time': datetime.datetime(2023, 1, 23, 9, 57, 7, 971506, tzinfo=<UTC>), 'is_on': True}]

should truncate to

<TimescaleQuerySet [
{'time': datetime.datetime(2023, 1, 23, 10, 57, 7, 971506, tzinfo=<UTC>), 'is_on': True},
{'time': datetime.datetime(2023, 1, 23, 10, 53, 20, 646474, tzinfo=<UTC>), 'is_on': False}, 
{'time': datetime.datetime(2023, 1, 23, 10, 23, 11, 787303, tzinfo=<UTC>), 'is_on': True}]

I'm breaking my head over this. Is there an elegant way to achieve this? I want to avoid looping over the whole queryset, it's just too slow when theres >1000 results.

Back to Top