[Answered ]-Django: Get the next and previous item IDs for a specific item given multiple OR parameters

2πŸ‘

βœ…

I didn’t test any of this so might just be talking out my arse, but maybe it’s a starting point?

Edit: Oh, yes, you were pretty clear about the β€œOR” issue, but still I missed it. Trying again. The basic idea is to convert your queries into lists and merge the lists. But thinking on that now – I think you can create actual querysets yourself – not that it might be useful in this case? You could do the common heavy lifting of the OR in the function then pass back a queryset which can be further manipulated by the view.

def get_next(item, brand=None, max_price=None)
    """Returns the next item to the one provided"""

    # apply limits to brand/price as specified
    if brand is not None:
         brand_candy = Item.objects.filter(brand=brand)\
                              .values_list('id','update_date')
    if max_price is not None
         price_candy = Item.objects.filter(price__lt=max_price)\
                              .values_list('id','update_date')

    # arrange all candidates into a joined list
    # TODO: finish this to merge the lists and sort by update_date
    ids = brand_candy.join(price_candy)

    # find the location of the current item in the list 
    # TODO: handle not being there
    idx = ids.index(item.id)

    # TODO: handle edges of the list
    next_idx = idx + 1

    # pluck out the next item
    return Item.objects.get(id=ids[next_idx])
πŸ‘€John Mee

Leave a comment