Is there a clever way to get the previous/next item using the Django ORM?

前端 未结 3 809
谎友^
谎友^ 2020-12-29 05:50

Say I have a list of photos ordered by creation date, as follows:

class Photo(models.Model):
    title = models.Char()
    image = models.Image()
    created         


        
3条回答
  •  执笔经年
    2020-12-29 06:44

    get_next_by_foo and get_previous_by_foo are handy, but very limited - they don't help you if you're ordering on more than one field, or a non-date field.

    I wrote django-next-prev as a more generic implementation of the same idea. In your case you could just do this, since you've set the ordering in your Meta:

    from next_prev import next_in_order, prev_in_order
    from .models import Photo
    
    photo = Photo.objects.get(...)
    next = next_in_order(photo)
    prev = prev_in_order(photo)
    

    If you wanted to order on some other combination of fields, just pass the queryset:

    photos = Photo.objects.order_by('title')
    photo = photos.get(...)
    next = next_in_order(photo, qs=photos)
    

提交回复
热议问题