I have used a similar approach but sometimes it can fail if rows have been deleted. Thus you should only use this method if you know that all of the ID's from 1 to 'max' still exist (as a side point - if you do know they all exist, a count may be faster than a Max aggregate).
Comment
I have used a similar approach but sometimes it can fail if rows have been deleted. Thus you should only use this method if you know that all of the ID's from 1 to 'max' still exist (as a side point - if you do know they all exist, a count may be faster than a Max aggregate).
Anyway, to get around this I used something like;
model.objects.filter(id__gte=randint(1, max_))[0]
Replies
if you get a random id that doesn't exist the loop will just try another number until it has rounded up as many as it needs.
A count is never faster than a MAX aggregate. Certainly not in Postgres