I've a queryset
which I want to sort using one of the columns, say date1
, and if the value of date1
is None
then use another column date2
for sorting and if date2
is also None
then use datetime.max
. So, this is what I came up with :
queryset = sorted(queryset, key= lambda row: row.date1 if row.date1 else row.date2 if row.date2 else datetime.max)
and then for paginating (with say 20 in one page) I'm sending back the id
of last record of previous request and using that to get the next 20 items (since after sorting ids are now in in random order). Also the entries can be deleted by the users so, using Paginator.page
and just fetching the consecutive pages in requests won't work.
This is how I find the index of the lastRecord
for getting the next 20:
lastRecordIndex = next(i for (i, d) in enumerate(queryset) if d.id == lastRecord)
queryset = queryset[lastRecordIndex+1: lastRecordIndex+20+1]
So, the problem is that this approach works, but is way too slow. Is there anything better I can do? using raw query or something else in django
?