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

前端 未结 3 813
谎友^
谎友^ 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:34

    You're in luck! Django creates get_next_by_foo and get_previous_by_foo methods by default for DateField & DateTimeField as long as they do not have null=True.

    For example:

    >>> from foo.models import Request
    >>> r = Request.objects.get(id=1)
    >>> r.get_next_by_created()
    
    

    And if you reach the end of a set it will raise a DoesNotExist exception, which you could easily use as a trigger to return to the beginning of the set:

    >>> r2 = r.get_next_by_created()
    >>> r2.get_next_by_created()
    ...
    DoesNotExist: Request matching query does not exist.
    

    Further reading: Extra instance methods

提交回复
热议问题