Search code examples
pythondjangomodelalphabetical

Creating a django query that will retrieve the previous and next object based on alphabetical order


I have a django model that looks something like this:

class Definition
    name = models.CharField(max_length=254)
    text = models.TextField()

If I do the following query:

animal = Definition.objects.get(name='Owl')

and if I have the following definitions with these names in my database:

Elephant, Owl, Zebra, Human

is there a way to do a django query(ies) that will show me the previous and the next Definitions based on the animal object based on alphabetical order of the name field in the model?

I know that there are ways of getting previous/next based on datetime fields, but I am not so sure for this case.


Solution

  • I don't know of any way of doing this in less than three queries.

    target = 'Owl'
    animal = Definition.objects.get(name=target)
    previous_animal = Definition.objects.order_by('name').filter(name__lt=target)[0]
    next_animal = Definition.objects.order_by('name').filter(name__gt=target)[0]