Note that there are some explanatory texts on larger screens.

plurals
  1. POGet records before and after current selection in Django query
    primarykey
    data
    text
    <p>It sounds like an odd one but it's a really simple idea. I'm trying to make a simple Flickr for a website I'm building. This specific problem comes when I want to show a single photo (from my <code>Photo</code> model) on the page but I also want to show the image before it in the stream and the image after it.</p> <p>If I were only sorting these streams by date, or was only sorting by ID, that might be simpler... But I'm not. I want to allow the user to sort and filter by a whole variety of methods. The sorting is simple. I've done that and I have a result-set, containing 0-many <code>Photo</code>s.</p> <p>If I want a single <code>Photo</code>, I start off with that filtered/sorted/etc stream. From it I need to get the current <code>Photo</code>, the <code>Photo</code> before it and the <code>Photo</code> after it.</p> <p>Here's what I'm looking at, at the moment.</p> <pre><code>prev = None next = None photo = None for i in range(1, filtered_queryset.count()): if filtered_queryset[i].pk = desired_pk: if i&gt;1: prev = filtered_queryset[i-1] if i&lt;filtered_queryset.count(): next = filtered_queryset[i+1] photo = filtered_queryset[i] break </code></pre> <p>It just seems disgustingly messy. And inefficient. Oh my lord, so inefficient. Can anybody improve on it though?</p> <p>Django queries are late-binding, so it would be nice to make use of that though I guess that might be impossible given my horrible restrictions.</p> <p>Edit: it occurs to me that I can just chuck in some SQL to re-filter queryset. If there's a way of selecting something with its two (or one, or zero) closest neighbours with SQL, I'd love to know!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload