Question

I am having a problem selecting next and previous records for my imaging site. Scenrio is pretty simple. but it made me a bit confused

I have list of images, sorted by the date they are added. (most recent earlier).

Picture.objects.all().order_by('-created_at')

When a user opens an image, i have to give link to the next and previous picture.

image = Picture.objects.get(id=pic_id)
next = Picture.objects.filter(created_at__lte=image.created_at)
previous = Picture.objects.filter(created_at__gte=image.created_at)

if next:
    next = next.exclude(id=image.id).order_by('-created_at')[0]
if previous:
    previous = previous.exclude(id=image.id).order_by('created_at')[0]

return (next, previous)

The problem here is, when two or more pictures have same created_at date, then there is a problem, that less than or equal check fails. If i restrict it to to less than than the Pic with the same date and time is not selected in either next or previous. `

(Multi File upload saves images in the db at same time)

Please check the code, and see where i need improvement.

Thanks.

Was it helpful?

Solution

As you have realised using just the created at date doesn't give you deterministic sort, you should also sort by the id of the pictures. The previous picture is then one with a created date less than the current image, or with the same created date and the previous id.

Because this is a complicated query you need to use Q objects.

next = Picture.objects.filter(Q(created_at__lt=image.created_at) | Q(created_at=image.created_at, id__lt=image.id))

if next:
    next = next.order_by("-created_at", "id")[0]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top