I’ve got a basic Item model in my Django app:
class Item(models.Model):
name = models.CharField(max_length=200)
brand = models.ForeignKey(User, related_name='items')
price = models.CharField(max_length=10)
upload_date = models.DateTimeField(auto_now=False, auto_now_add=True)
For a given item, I am trying to get the next and previous items in the db.
I know I can do this using Django’s built-in Model.get_next_by_FOO(**kwargs), which works perfectly well with the upload_date field, but I need to get the previous and next items given certain OR parameters (for example items that have a certain brand OR are under a certain price).
I can get the previous item using a query like this:
previous_item = Item.objects.filter(id__lt=item.id).filter(Q(brand__in=brands)|Q(price__lt=100))[:1]
My problem is with the next item. Running the same query for the next item results in the most recent item overall that meets the criteria, not the item that comes after the current item in the database. I understand that this is because of the way Django queries the database, but don’t know how to get around it to get the item that comes directly after the current item that also meets the criteria.
Is there a fast, simple way to get the next item for a specific item given multiple OR parameters?
Thanks!
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.