Django ORM: select until value in column changes

I want to get newest events until the first change.

This is my data (sorted by timestamp):

# EventModel
id |  event    | timestamp
---+-----------+-----------
1  | birthday  | 5
2  | birthday  | 4
3  | wedding   | 3
4  | null      | 2
5  | birthday  | 1

This is my desired output:

<QuerySet [{'id': 1, 'event': 'birthday', 'timestamp': 5}, {'id': 2, 'event': 'birthday', 'timestamp': 4}]>

Please note that there is also event=birthday where id=5, but I don't want it in the output.

The newest event can be null and that's ok.

I tried with Subquery:

from django.db.models import Subquery

subquery = EventModel.objects.order_by("-timestamp").values("event")[:1]
EventModel.objects.filter(event=Subquery(subquery))

But this gives me also row with id=5.

Back to Top