What is the correct way to get the previous page of results given an NDB cursor?

前端 未结 2 1845
情深已故
情深已故 2020-12-29 09:59

I\'m working on providing an API via GAE that will allow users to page forwards and backwards through a set of entities. I\'ve reviewed the section about cursors on the NDB

2条回答
  •  爱一瞬间的悲伤
    2020-12-29 10:23

    To make the example from the docs a little clearer let's forget about the datastore for a moment and work with a list instead:

    # some_list = [4, 6, 1, 12, 15, 0, 3, 7, 10, 11, 8, 2, 9, 14, 5, 13]
    
    # Set up.
    q = Bar.query()
    
    q_forward = q.order(Bar.key)
    # This puts the elements of our list into the following order:
    # ordered_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
    
    q_reverse = q.order(-Bar.key)
    # Now we reversed the order for backwards paging: 
    # reversed_list = [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    
    # Fetch a page going forward.
    
    bars, cursor, more = q_forward.fetch_page(10)
    # This fetches the first 10 elements from ordered_list(!) 
    # and yields the following:
    # bars = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    # cursor = [... 9, CURSOR-> 10 ...]
    # more = True
    # Please notice the right-facing cursor.
    
    # Fetch the same page going backward.
    
    rev_cursor = cursor.reversed()
    # Now the cursor is facing to the left:
    # rev_cursor = [... 9, <-CURSOR 10 ...]
    
    bars1, cursor1, more1 = q_reverse.fetch_page(10, start_cursor=rev_cursor)
    # This uses reversed_list(!), starts at rev_cursor and fetches 
    # the first ten elements to it's left:
    # bars1 = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    

    So the example from the docs fetches the same page from two different directions in two differents orders. This is not what you want to achieve.

    It seems you already found a solution that covers your use case pretty well but let me suggest another:

    Simply reuse cursor1 to go back to page2.
    If we're talking frontend and the current page is page3, this would mean assigning cursor3 to the 'next'-button and cursor1 to the 'previous'-button.

    That way you have to reverse neither the query nor the cursor(s).

提交回复
热议问题