72211

Annotate objects in a queryset with next and previous object ids

Question:

How do I annotate the objects in a Django ORM queryset so that every items contain IDs of the the object before (previous) and the one after (next)? I am using PostgreSQL and Django 1.11.

Answer1:

You could use the <a href="https://www.postgresql.org/docs/current/static/functions-window.html" rel="nofollow">window functions lag() and lead()</a>:

SELECT * , lag(id) OVER (ORDER BY id) AS prev_id -- same order as query , lead(id) OVER (ORDER BY id) AS next_id -- same order as query FROM tbl ORDER BY id;

Recommend

  • Multiple table or one single table?
  • Pygame - Collision detection with two CIRCLES
  • Longest path between from a source to certain nodes in a DAG
  • iOS: Customise UITextField's inputView size
  • Bash for loop over array with files from (*) shows only first element
  • Android/java: Transition / Migration from ProGuard to R8?
  • send Post request to PHP Server
  • entity framework code first - shared 1-to-many entity
  • Pass empty strings in cmake?
  • Calling a web server inside Jupyterhub without connection failed
  • JSON printing all paths from root to leaf
  • C99′s Fixed-Width Integer Types
  • Problem in JPA-Mapping
  • about iOS target version and SDK version
  • How to achieve density/heat map effect in iOS (iPhone/iPad)?
  • Null Space Binary Matrix : Java
  • Parse and remove special characters in java regex
  • forever does not start on server reboot [duplicate]
  • Bulk loading into PostgreSQL from a remote client
  • Special characters (ë) in JSON-response
  • Finding all XML nodes between each two processing instructions
  • React/Redux. Access state from other component
  • date changes on export kendoGrid
  • if you have a DLL creating a bitmap in memory, how to return it to the browser?
  • No Gradle file syntax highlighting in Eclipse Mars.2
  • Can't hide status bar in AVPlayerViewController's portrait mode
  • How to display youtube video on HTML page? [closed]
  • Excel File upload in asp.net using SqlBulkCopy
  • All Event listing on specified date in Google Calender api (V3) in java?
  • How to define something in JavaScript [closed]
  • Runtime complexity of getting the length of a string in different representations
  • JavaScript Regex to Match Boundaries of Words with diacritics
  • Amazon Elastick BeanStalk error: Failed to create the AWS Elastic Beanstalk application version
  • How to decleare char *const argv[] in swift [duplicate]
  • How to handle div that is created dynamically in a table
  • Grails - How to implement a foreign key relationship not using an id column?
  • Access to a Matlab gui from the web
  • convert json to excel in java
  • Time Complexity of Fibonacci Algorithm [duplicate]
  • XSLT Transformation to validate rules in XML document