La mejor manera de obtener las imágenes siguientes y anteriores Django
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).
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') if previous: previous = previous.exclude(id=image.id).order_by('created_at') 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.
preguntado el 04 de marzo de 14 a las 11:03
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 objetos.
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")
Thanks Andrew, it seems to work fine, How can i add another filter using Q? i want to filter the picture records under city. where city = this.city. i added another .filter() and seems working fine. but i think i should ask this too. - AJ
Other than Q() its working perfectly, thank you for sorting out my confusion ... +1 - AJ
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas python mysql django model or haz tu propia pregunta.
As per Andrew's answer you need to sort on the id as well. Just thought it's worth mentioning using a
DateTimeFielden lugar de solo un
DateFieldwould also help - Anentropic